<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    :destroyOnClose="true"
    :class="'jee-outer-modal'"
    :okButtonProps="{ props: { disabled: disableSubmit } }"
    :okText="disableSubmit ? '关闭' : '确定'"
    :switchFullscreen="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <div class="upload-file-container" v-if="activeKey === '0'">
          <div class="upload-header">
            <span class="upload-title">上传窗型确认文件</span>
            <span class="upload-desc">解析成功后显示下方信息</span>
          </div>

          <!-- 上传区域 -->
          <div class="upload-area">
            <a-upload-dragger
              name="file"
              :multiple="false"
              :action="url.uploadWindowConfirmationFile"
              :headers="tokenHeader"
              :beforeUpload="beforeUpload"
              @change="handleFileUpload"
              :showUploadList="false"
              accept=".xlsx,.xls"
            >
              <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
              </p>
              <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p class="ant-upload-hint">仅支持上传Excel文件(.xlsx, .xls)</p>
            </a-upload-dragger>
          </div>

          <!-- 上传状态显示 -->
          <div class="upload-status" v-if="uploadStatus !== ''">
            <a-alert :type="uploadStatus === 'success' ? 'success' : 'error'" :message="uploadMessage" show-icon />
          </div>

          <!-- 解析结果显示 -->
          <div
            class="parse-result"
            v-if="uploadStatus === 'success' && parseResult && parseResult.details && parseResult.details.length > 0"
          >
            <a-divider>解析结果</a-divider>

            <div style="max-height: 400px; overflow: auto">
              <a-table
                :columns="detailColumns"
                :dataSource="parseResult.details"
                :pagination="false"
                :rowKey="(record) => record.key || record.windowNo"
                bordered
              >
                <template slot="photoUrlSlot" slot-scope="text, record">
                  <div v-if="text" class="drawing-thumbnail-container" @click="previewDrawing(text, record)">
                    <img
                      v-if="isImageFile(text)"
                      :src="getFullImageUrl(text)"
                      class="drawing-thumbnail"
                      alt="图纸缩略图"
                      @error="handleImageError"
                    />
                    <a-icon v-else type="file-pdf" class="file-icon" />
                    <span class="thumbnail-filename">{{ getFileName(text) }}</span>
                  </div>
                  <span v-else>无图纸</span>
                </template>
                <template slot="quantitySlot" slot-scope="text, record, index">
                  <a-input-number
                    v-model="parseResult.details[index].quantity"
                    :min="1"
                    :precision="0"
                    style="width: 80px"
                    @change="(value) => handleQuantityChange(record, value, index)"
                  />
                </template>
              </a-table>
            </div>

            <!-- 添加下一步按钮 -->
            <div style="margin-top: 16px; text-align: center">
              <a-button type="primary" @click="goToNextStep">下一步</a-button>
            </div>
          </div>
        </div>
        <a-tabs v-else v-model="activeKey" @change="handleTabChange" :animated="false" :forceRender="true">
          <!-- 订单信息 -->
          <a-tab-pane key="1" tab="订单信息">
            <a-row>
              <a-col :span="12">
                <a-form-item label="订单编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input
                    v-decorator="['orderNo', { initialValue: model.orderNo }]"
                    placeholder="系统自动生成"
                    :disabled="true"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="销售负责人" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-select-employee-modal
                    v-decorator="['salesPersonId', validatorRules.salesPersonId]"
                    :trigger-change="true"
                    :multiple="false"
                    :departName="'销售部'"
                    placeholder="请选择销售负责人"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="12">
                <a-form-item label="下单日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker
                    style="width: 100%"
                    v-decorator="['orderDate', validatorRules.orderDate]"
                    placeholder="请选择下单日期"
                    :getCalendarContainer="getParentModal"
                    format="YYYY-MM-DD"
                    :allowClear="false"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="交付日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker
                    style="width: 100%"
                    v-decorator="['deliveryDate', validatorRules.deliveryDate]"
                    placeholder="请选择交付日期"
                    :getCalendarContainer="getParentModal"
                    format="YYYY-MM-DD"
                    :allowClear="false"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="12">
                <a-form-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-select-customer-modal
                    v-decorator="['customerId', validatorRules.customerId]"
                    @change="onCustomerChange"
                    :disabled="disableSubmit"
                  />
                  <a-input v-decorator="['customerName']" type="hidden" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="工程" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-select-project-modal
                    v-decorator="[
                      'projectId',
                      {
                        rules: [{ required: true, message: '请选择工程!' }],
                        initialValue: model.projectId,
                      },
                    ]"
                    :customerId="customerId"
                    @change="onProjectChange"
                    :disabled="disableSubmit"
                  />
                  <a-input v-decorator="['projectName']" type="hidden" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="24">
                <a-form-item label="订单描述" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                  <a-textarea
                    placeholder="请输入订单描述"
                    v-decorator="['description']"
                    :autoSize="{ minRows: 3, maxRows: 6 }"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>

          <!-- 财务信息 -->
          <a-tab-pane tab="财务信息" key="2">
            <a-spin :spinning="confirmLoading" class="finance-tab-content">
              <!-- 添加财务信息汇总卡片 -->
              <a-card title="财务信息汇总" :bordered="false" style="margin-bottom: 16px">
                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-statistic
                      title="销售总额"
                      :value="model.totalAmount || 0"
                      :precision="2"
                      prefix="¥"
                      :valueStyle="{ color: '#3f8600' }"
                    >
                      <template v-if="!model.id && !disableSubmit" #suffix>
                        <a-button type="link" size="small" @click="showTotalAmountModal">
                          <a-icon type="edit" />
                        </a-button>
                      </template>
                    </a-statistic>
                  </a-col>
                  <a-col :span="8">
                    <a-statistic
                      title="成本汇总"
                      :value="model.totalCost || 0"
                      :precision="2"
                      prefix="¥"
                      :valueStyle="{ color: '#1890ff' }"
                    >
                      <template v-if="!model.id && !disableSubmit" #suffix>
                        <a-button type="link" size="small" @click="showTotalCostModal">
                          <a-icon type="edit" />
                        </a-button>
                      </template>
                    </a-statistic>
                  </a-col>
                  <a-col :span="8">
                    <a-statistic
                      title="利润"
                      :value="calculateProfit()"
                      :precision="2"
                      prefix="¥"
                      :valueStyle="calculateProfit() > 0 ? { color: '#52c41a' } : { color: '#cf1322' }"
                    />
                  </a-col>
                </a-row>
                <a-row :gutter="16" style="margin-top: 16px">
                  <a-col :span="8">
                    <a-statistic
                      title="实收金额"
                      :value="model.receivedAmount || 0"
                      :precision="2"
                      prefix="¥"
                      :valueStyle="{ color: '#52c41a' }"
                    />
                  </a-col>
                  <a-col :span="8">
                    <a-statistic
                      title="未收款金额"
                      :value="model.unpaidAmount || 0"
                      :precision="2"
                      prefix="¥"
                      :valueStyle="(model.unpaidAmount || 0) > 0 ? { color: '#cf1322' } : { color: '#52c41a' }"
                    />
                  </a-col>
                </a-row>
              </a-card>

              <!-- 交易记录表格 -->
              <a-card title="交易记录" :bordered="false">
                <div v-if="!disableSubmit" class="transaction-table-header">
                  <a-button type="primary" icon="plus" @click="handleAddTransaction">添加交易记录</a-button>
                </div>
                <a-table
                  :columns="disableSubmit ? transactionColumnsReadOnly : transactionColumns"
                  :dataSource="transactionRecords"
                  :pagination="false"
                  :rowKey="(record) => record.id || record.key"
                  class="transaction-table finance-table j-table-force-nowrap"
                  size="middle"
                  bordered
                  style="margin-top: 8px"
                  :scroll="{ y: 300, x: true }"
                >
                  <template slot="transactionTypeSlot" slot-scope="text, record">
                    <j-dict-select-tag
                      v-if="record.editable && !disableSubmit"
                      v-model="record.transactionType"
                      placeholder="请选择交易类型"
                      dictCode="transaction_type"
                      type="list"
                      :getPopupContainer="getParentModal"
                    />
                    <j-dict-tag v-else :value="text" dictCode="transaction_type" />
                  </template>

                  <template slot="paymentMethodSlot" slot-scope="text, record">
                    <j-dict-select-tag
                      v-if="record.editable && !disableSubmit"
                      v-model="record.paymentMethod"
                      placeholder="请选择支付方式"
                      dictCode="payment_method"
                      type="list"
                      :getPopupContainer="getParentModal"
                    />
                    <j-dict-tag v-else :value="text" dictCode="payment_method" />
                  </template>

                  <template slot="amountSlot" slot-scope="text, record">
                    <a-input-number
                      v-if="record.editable && !disableSubmit"
                      v-model="record.amount"
                      style="width: 100%"
                      :precision="2"
                      :min="0"
                    />
                    <span
                      v-else
                      style="font-weight: 500"
                      :style="{ color: parseFloat(text) < 0 ? '#f5222d' : '#52c41a' }"
                    >
                      {{ text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00' }}
                    </span>
                  </template>

                  <template slot="transactionPersonIdSlot" slot-scope="text, record">
                    <j-select-employee-modal
                      v-if="record.editable && !disableSubmit"
                      v-model="record.transactionPersonId"
                      :trigger-change="true"
                      :multiple="false"
                      :departName="'销售部'"
                      placeholder="请选择交易人员"
                      @change="(value, option) => handlePersonChange(value, option, record)"
                      style="width: 100%"
                      :getPopupContainer="getParentModal"
                    ></j-select-employee-modal>
                    <span v-else>{{ record.transactionPersonName }}</span>
                  </template>

                  <template slot="paymentVoucherSlot" slot-scope="text, record">
                    <j-upload
                      v-if="record.editable && !disableSubmit"
                      v-model="record.paymentVoucher"
                      :uploadAction="uploadAction"
                      :multiple="false"
                      :returnUrl="true"
                    ></j-upload>
                    <div
                      v-else-if="record.paymentVoucher && isImageFile(record.paymentVoucher)"
                      class="voucher-thumbnail-container"
                      @click="previewVoucher(record.paymentVoucher)"
                    >
                      <img
                        :src="getFullImageUrl(record.paymentVoucher)"
                        class="voucher-thumbnail"
                        alt="凭证缩略图"
                        @error="handleImageError"
                      />
                    </div>
                    <div
                      v-else-if="record.transactionVoucher && isImageFile(record.transactionVoucher)"
                      class="voucher-thumbnail-container"
                      @click="previewVoucher(record.transactionVoucher)"
                    >
                      <img
                        :src="getFullImageUrl(record.transactionVoucher)"
                        class="voucher-thumbnail"
                        alt="凭证缩略图"
                        @error="handleImageError"
                      />
                    </div>
                    <a
                      v-else-if="record.paymentVoucher"
                      @click="previewVoucher(record.paymentVoucher)"
                      class="voucher-link"
                      >查看凭证</a
                    >
                    <a
                      v-else-if="record.transactionVoucher"
                      @click="previewVoucher(record.transactionVoucher)"
                      class="voucher-link"
                      >查看凭证</a
                    >
                    <span v-else>无</span>
                  </template>

                  <template slot="descriptionSlot" slot-scope="text, record">
                    <a-textarea
                      v-if="record.editable && !disableSubmit"
                      v-model="record.description"
                      placeholder="请输入交易描述"
                      :rows="2"
                      :autoSize="{ minRows: 2, maxRows: 4 }"
                      class="description-textarea"
                    />
                    <div v-else class="description-content">
                      <a-tooltip :title="text" placement="topLeft" v-if="text && text.length > 30">
                        <span>{{ text.slice(0, 30) }}...</span>
                      </a-tooltip>
                      <span v-else-if="text">{{ text }}</span>
                      <span v-else class="empty-description">暂无描述信息</span>
                    </div>
                  </template>

                  <template slot="actionSlot" slot-scope="text, record, index">
                    <div v-if="record.editable && !disableSubmit">
                      <a @click="() => saveTransaction(record, index)" class="action-btn">保存</a>
                      <a-divider type="vertical" />
                      <a @click="() => cancelEdit(record, index)" class="action-btn">取消</a>
                    </div>
                    <div v-else-if="!disableSubmit">
                      <a @click="() => editTransaction(record, index)" class="action-btn">编辑</a>
                      <a-divider type="vertical" />
                      <a-popconfirm title="确定删除吗?" @confirm="() => removeTransaction(record, index)">
                        <a class="action-btn">删除</a>
                      </a-popconfirm>
                    </div>
                  </template>
                </a-table>
              </a-card>
            </a-spin>
          </a-tab-pane>

          <!-- 产品明细 -->
          <a-tab-pane key="3" tab="产品明细">
            <div style="max-height: 400px; overflow: auto; background-color: #ffffff">
              <a-table
                :columns="disableSubmit ? detailColumnsReadOnly : detailColumns"
                :dataSource="detailDataSource"
                :pagination="false"
                :rowKey="(record) => record.key || record.windowNo"
                bordered
              >
                <template slot="photoUrlSlot" slot-scope="text, record">
                  <div v-if="text" class="drawing-thumbnail-container" @click="previewDrawing(text, record)">
                    <img
                      v-if="isImageFile(text)"
                      :src="getFullImageUrl(text)"
                      class="drawing-thumbnail"
                      alt="图纸缩略图"
                      @error="handleImageError"
                    />
                    <a-icon v-else type="file-pdf" class="file-icon" />
                    <span class="thumbnail-filename">{{ getFileName(text) }}</span>
                  </div>
                  <span v-else>无图纸</span>
                </template>

                <template slot="operation" slot-scope="text, record, index">
                  <a-button type="link" size="small" @click="handleViewDetailInfo(record)">详情</a-button>
                  <a-divider type="vertical" v-if="!disableSubmit" />
                  <a-divider type="vertical" v-if="!disableSubmit" />
                  <a-popconfirm
                    v-if="!disableSubmit"
                    title="确定删除吗?"
                    @confirm="() => handleRemoveDetail(record, index)"
                  >
                    <a>删除</a>
                  </a-popconfirm>
                </template>

                <template slot="detailOperation" slot-scope="text, record">
                  <a-button type="link" size="small" @click="handleViewDetailInfo(record)">详情</a-button>
                </template>
              </a-table>
            </div>
          </a-tab-pane>

          <!-- 订单进度 - 仅在编辑和查看模式下显示 -->
          <a-tab-pane key="4" tab="订单进度" v-if="model.id">
            <div class="progress-container">
              <div class="progress-header">
                <h3>订单进度记录</h3>
              </div>
              <a-timeline class="order-progress-timeline">
                <a-timeline-item
                  v-for="(progress, index) in progressList"
                  :key="index"
                  :color="getProgressColor(progress.newStatus, index === 0)"
                >
                  <div class="progress-item" :class="{ 'latest-item': index === 0 }">
                    <div class="progress-item-header">
                      <div class="progress-main-info">
                        <span class="progress-type">
                          <a-tag :color="getProgressColor(progress.newStatus, index === 0)">
                            {{ getProgressTypeText(progress.newStatus) }}
                          </a-tag>
                        </span>
                        <span class="progress-time">{{ progress.createTime }}</span>
                      </div>
                    </div>
                    <div class="progress-content">
                      <div class="progress-reason">
                        <span class="reason-label">变更原因：</span>
                        <span class="reason-content">{{ progress.changeReason || '无' }}</span>
                      </div>
                    </div>
                    <div class="progress-footer">
                      <span class="progress-operator"
                        >操作人: {{ progress.operatorName || progress.createBy_dictText || progress.createBy }}</span
                      >
                      <span class="update-time" v-if="progress.updateTime">更新于: {{ progress.updateTime }}</span>
                    </div>
                  </div>
                </a-timeline-item>

                <a-timeline-item v-if="progressList.length === 0" color="gray">
                  <div class="empty-progress">
                    <a-empty description="暂无进度记录" />
                  </div>
                </a-timeline-item>
              </a-timeline>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-spin>

    <!-- 客户选择模态框 -->
    <customer-modal ref="customerModal" @ok="handleCustomerSelected"></customer-modal>

    <!-- 工程选择模态框 -->
    <project-select-modal ref="projectSelectModal" @ok="handleProjectSelected"></project-select-modal>

    <!-- 图纸预览模态框 -->
    <a-modal
      title="图纸预览"
      :visible="drawingPreviewVisible"
      @cancel="closeDrawingPreview"
      :footer="null"
      :width="1000"
      :destroyOnClose="true"
    >
      <div class="drawing-preview-container">
        <!-- 图片文件直接显示 -->
        <img
          v-if="isImageFile(currentDrawingUrl)"
          :src="currentDrawingUrl"
          class="drawing-preview-image"
          @error="handleImageError"
        />
        <!-- 非图片文件使用iframe嵌入显示 -->
        <iframe
          v-else
          :src="getPreviewUrl(currentDrawingUrl)"
          class="drawing-preview-iframe"
          frameborder="0"
          allowfullscreen
        ></iframe>
      </div>
    </a-modal>

    <!-- 销售总额编辑模态框 -->
    <a-modal
      title="编辑销售总额"
      :visible="totalAmountModalVisible"
      @ok="handleTotalAmountOk"
      @cancel="handleTotalAmountCancel"
      :maskClosable="false"
    >
      <a-form :form="totalAmountForm">
        <a-form-item label="销售总额">
          <a-input-number
            style="width: 100%"
            v-decorator="['totalAmount', { rules: [{ required: true, message: '请输入销售总额!' }] }]"
            placeholder="请输入销售总额"
            :disabled="disableSubmit"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 成本汇总编辑模态框 -->
    <a-modal
      title="编辑成本汇总"
      :visible="totalCostModalVisible"
      @ok="handleTotalCostOk"
      @cancel="handleTotalCostCancel"
      :maskClosable="false"
    >
      <a-form :form="totalCostForm">
        <a-form-item label="成本汇总">
          <a-input-number
            style="width: 100%"
            v-decorator="['totalCost', { rules: [{ required: true, message: '请输入成本汇总!' }] }]"
            placeholder="请输入成本汇总"
            :disabled="disableSubmit"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 产品详情信息弹窗 -->
    <a-modal
      title="产品详细信息"
      :visible="detailInfoVisible"
      @cancel="closeDetailInfoModal"
      :footer="null"
      :width="900"
      :destroyOnClose="true"
    >
      <a-spin :spinning="detailInfoLoading">
        <a-tabs defaultActiveKey="1">
          <a-tab-pane key="1" tab="配件信息">
            <a-table
              :columns="isChangfengType ? accessoriesColumnsCf : accessoriesColumnsXge"
              :dataSource="accessoriesList"
              :pagination="false"
              :rowKey="(record) => record.id || record.serialNo"
              bordered
              size="middle"
              :scroll="{ x: 'max-content' }"
              style="width: 100%"
            ></a-table>
          </a-tab-pane>
          <a-tab-pane key="2" tab="玻璃尺寸">
            <a-table
              :columns="isChangfengType ? glassSizeColumnsCf : glassSizeColumnsXge"
              :dataSource="glassSizeList"
              :pagination="false"
              :rowKey="(record) => record.id || record.serialNo"
              bordered
              size="middle"
              :scroll="{ x: 'max-content' }"
              style="width: 100%"
            ></a-table>
          </a-tab-pane>
          <a-tab-pane key="3" tab="型材尺寸">
            <a-table
              :columns="isChangfengType ? profileSizeColumnsCf : profileSizeColumnsXge"
              :dataSource="profileSizeList"
              :pagination="false"
              :rowKey="(record) => record.id || record.serialNo"
              bordered
              size="middle"
              :scroll="{ x: 'max-content' }"
              style="width: 100%"
            ></a-table>
          </a-tab-pane>
        </a-tabs>
      </a-spin>
    </a-modal>
  </a-modal>
</template>

<script>
import { getAction, postAction, uploadAction, deleteAction, putAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Vue from 'vue'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import JSelectEmployeeModal from '@/components/jeecgbiz/JSelectEmployeeModal'
import ProductDetailModal from './ProductDetailModal'
import CustomerModal from '@/views/crm/modules/CustomerModal'
import ProjectSelectModal from './ProjectSelectModal'
import JSelectCustomerModal from '@/components/jeecgbiz/JSelectCustomerModal'
import JSelectProjectModal from '@/components/jeecgbiz/JSelectProjectModal'
import { getFileAccessHttpUrl } from '@/api/manage'
import '@/assets/less/TableExpand.less'

export default {
  name: 'ProductOrderModal',
  components: {
    JSelectEmployeeModal,
    ProductDetailModal,
    CustomerModal,
    ProjectSelectModal,
    JSelectCustomerModal,
    JSelectProjectModal,
  },
  mixins: [JEditableTableMixin],
  data() {
    return {
      title: '操作',
      visible: false,
      activeKey: '0', // 默认显示上传文件页面
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      confirmLoading: false,
      form: null, // 将在mounted中初始化
      disableSubmit: false, // 是否禁用提交按钮

      // 添加临时交易记录数组，用于存储新增订单时的交易记录
      tempTransactionRecords: [],

      // 添加进度记录列表
      progressList: [],

      // 进度弹窗相关
      progressModalVisible: false,
      progressForm: null, // 将在mounted中初始化
      currentProgress: null,
      progressEditIndex: -1,

      // 财务信息相关
      financeColumns: [
        {
          title: '财务项目',
          dataIndex: 'label',
          key: 'label',
          width: 150,
          align: 'right',
        },
        {
          title: '值',
          dataIndex: 'value',
          key: 'value',
          className: 'amount-column',
          scopedSlots: { customRender: 'valueSlot' },
        },
      ],
      financeData: [
        { key: 'totalAmount', label: '销售总额', value: 0, scopedSlot: 'totalAmountSlot' },
        { key: 'prepayment', label: '预付款', value: 0, scopedSlot: 'prepaymentSlot' },
        { key: 'totalCost', label: '成本汇总', value: 0, scopedSlot: 'totalCostSlot' },
        { key: 'profit', label: '销售利润', value: 0, scopedSlot: 'profitSlot' },
      ],

      validatorRules: {
        salesPersonId: { rules: [{ required: true, message: '请选择销售负责人!' }] },
        orderDate: { rules: [{ required: true, message: '请选择下单日期!' }] },
        deliveryDate: { rules: [{ required: true, message: '请选择交付日期!' }] },
        customerId: { rules: [{ required: true, message: '请选择客户!' }] },
        totalAmount: { rules: [{ required: true, message: '请输入销售总额!' }] },
        optimizationSoftwareType: { rules: [{ required: true, message: '请选择优化软件类型!' }] },
      },

      // 交易记录相关
      transactionRecords: [],
      transactionColumns: [
        {
          title: '交易时间',
          dataIndex: 'transactionTime',
          key: 'transactionTime',
          width: 150,
          customRender: (text) => {
            return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : ''
          },
        },
        {
          title: '交易类型',
          dataIndex: 'transactionType',
          key: 'transactionType',
          width: 120,
          scopedSlots: { customRender: 'transactionTypeSlot' },
        },
        {
          title: '支付方式',
          dataIndex: 'paymentMethod',
          key: 'paymentMethod',
          width: 120,
          scopedSlots: { customRender: 'paymentMethodSlot' },
        },
        {
          title: '金额',
          dataIndex: 'amount',
          key: 'amount',
          width: 120,
          align: 'center',
          className: 'amount-column',
          scopedSlots: { customRender: 'amountSlot' },
        },
        {
          title: '人员',
          dataIndex: 'transactionPersonName',
          key: 'createBy',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'transactionPersonIdSlot' },
        },
        {
          title: '凭证',
          dataIndex: 'paymentVoucher',
          key: 'paymentVoucher',
          width: 120,
          scopedSlots: { customRender: 'paymentVoucherSlot' },
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description',
          className: 'description-column',
          width: 200,
          ellipsis: true,
          scopedSlots: { customRender: 'descriptionSlot' },
        },
        {
          title: '操作',
          key: 'action',
          width: 120,
          className: 'action-column',
          scopedSlots: { customRender: 'actionSlot' },
        },
      ],
      editingTransaction: null,
      tempTransaction: {},

      // 产品明细
      detailTitle: '添加产品',
      detailVisible: false,
      detailForm: null, // 将在mounted中初始化
      detailDataSource: [],
      detailIndex: -1, // 当前编辑的明细索引，-1表示新增

      detailColumns: [
        {
          title: '窗号',
          dataIndex: 'windowNo',
          key: 'windowNo',
          width: 100,
        },
        {
          title: '系列',
          dataIndex: 'windowSeries',
          key: 'windowSeries',
          width: 150,
        },
        {
          title: '颜色',
          dataIndex: 'windowColor',
          key: 'windowColor',
          width: 150,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          key: 'quantity',
          width: 80,
          scopedSlots: { customRender: 'quantitySlot' },
        },
        {
          title: '总面积(㎡)',
          dataIndex: 'totalArea',
          key: 'totalArea',
          width: 120,
        },
        {
          title: '图纸',
          dataIndex: 'photoUrl',
          key: 'photoUrl',
          width: 100,
          scopedSlots: { customRender: 'photoUrlSlot' },
        },
        {
          title: '操作',
          key: 'action',
          width: 180,
          scopedSlots: { customRender: 'operation' },
        },
      ],
      // 详情模式下的产品明细表格列配置，不包含操作列
      detailColumnsReadOnly: [
        {
          title: '窗号',
          dataIndex: 'windowNo',
          key: 'windowNo',
          width: 100,
        },
        {
          title: '系列',
          dataIndex: 'windowSeries',
          key: 'windowSeries',
          width: 150,
        },
        {
          title: '颜色',
          dataIndex: 'windowColor',
          key: 'windowColor',
          width: 150,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          key: 'quantity',
          width: 80,
        },
        {
          title: '总面积(㎡)',
          dataIndex: 'totalArea',
          key: 'totalArea',
          width: 120,
        },
        {
          title: '图纸',
          dataIndex: 'photoUrl',
          key: 'photoUrl',
          width: 100,
          scopedSlots: { customRender: 'photoUrlSlot' },
        },
        {
          title: '操作',
          key: 'action',
          width: 100,
          scopedSlots: { customRender: 'detailOperation' },
        },
      ],

      // 上传窗型确认文件相关
      uploadStatus: '', // 上传状态：'' | 'uploading' | 'success' | 'error'
      uploadMessage: '', // 上传状态消息
      parseResult: null, // 解析结果

      url: {
        list: '/oms/productSalesOrder/list',
        add: '/oms/productSalesOrder/add',
        edit: '/oms/productSalesOrder/edit',
        delete: '/oms/productSalesOrder/delete',
        deleteBatch: '/oms/productSalesOrder/deleteBatch',
        exportXlsUrl: 'oms/productSalesOrder/exportXls',
        importExcelUrl: 'oms/productSalesOrder/importExcel',
        generateOrderNo: '/oms/productSalesOrder/generateOrderNo',
        uploadWindowConfirmationFile: '/jeecg-boot/oms/productSalesOrder/uploadWindowConfirmationFile',
        loadDetail: '/oms/productSalesOrder/detail/list',
        loadTransaction: '/oms/productSalesOrder/transaction/list',
        addTransaction: '/oms/productSalesOrder/transaction/add',
        editTransaction: '/oms/productSalesOrder/transaction/edit',
        deleteTransaction: '/oms/productSalesOrder/transaction/delete',
        loadProgress: '/oms/productSalesOrder/progress/list',
        addProgress: '/oms/productSalesOrder/progress/add',
        editProgress: '/oms/productSalesOrder/progress/edit',
        pageByOrderId: '/oms/productSalesOrder/transaction/pageByOrderId',
        progressPageByOrderId: '/oms/productSalesOrder/progress/pageByOrderId',
        getOrderDetailById: '/oms/productSalesOrder/queryById',
        loadAccessories: '/oms/cfAccessoriesTable/listByDetailIdAndType',
        loadGlassSize: '/oms/cfGlassSizeTable/listByDetailIdAndType',
        loadProfileSize: '/oms/cfProfileSizeTable/listByDetailIdAndType',
      },

      customerId: '', // 添加客户ID变量

      // 图纸预览相关
      drawingPreviewVisible: false,
      currentDrawingUrl: '',

      // 添加获取文件名的方法
      getFileName(url) {
        if (!url) return ''
        const parts = url.split('/')
        return parts[parts.length - 1]
      },

      // 添加销售总额编辑模态框相关变量
      totalAmountModalVisible: false,
      totalAmountForm: null,

      // 添加成本汇总编辑模态框相关变量
      totalCostModalVisible: false,
      totalCostForm: null,

      // 用户缓存
      userCache: {},

      // 产品详情弹窗相关
      detailInfoVisible: false,
      detailInfoLoading: false,
      currentDetailRecord: null,
      accessoriesList: [],
      glassSizeList: [],
      profileSizeList: [],

      // 长风系统配件列定义
      accessoriesColumnsCf: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '配件名称',
          dataIndex: 'accessoryName',
          width: 120,
        },
        {
          title: '规格',
          dataIndex: 'specification',
          width: 120,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 80,
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: 60,
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          width: 80,
        },
      ],

      // 新格尔系统配件列定义
      accessoriesColumnsXge: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 80,
        },
        {
          title: '配件编号',
          dataIndex: 'accessoryCode',
          width: 100,
        },
        {
          title: '配件名称',
          dataIndex: 'accessoryName',
          width: 120,
        },
        {
          title: '规格',
          dataIndex: 'specification',
          width: 120,
        },
        {
          title: '颜色',
          dataIndex: 'color',
          width: 80,
        },
        {
          title: '长度/数量',
          dataIndex: 'lengthQuantity',
          width: 100,
        },
      ],

      // 长风系统玻璃尺寸列定义
      glassSizeColumnsCf: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '玻璃宽',
          dataIndex: 'glassWidth',
          width: 80,
        },
        {
          title: '玻璃高',
          dataIndex: 'glassHeight',
          width: 80,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 60,
        },
        {
          title: '玻璃种类',
          dataIndex: 'glassType',
          width: 120,
        },
      ],

      // 新格尔系统玻璃尺寸列定义
      glassSizeColumnsXge: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 80,
        },
        {
          title: '玻璃名称',
          dataIndex: 'glassName',
          width: 120,
        },
        {
          title: '规格',
          dataIndex: 'specification',
          width: 100,
        },
        {
          title: '安装位置',
          dataIndex: 'installPosition',
          width: 100,
        },
        {
          title: '磨',
          dataIndex: 'frosted',
          width: 60,
        },
        {
          title: '宽',
          dataIndex: 'glassWidth',
          width: 80,
        },
        {
          title: '高',
          dataIndex: 'glassHeight',
          width: 80,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 60,
        },
      ],

      // 长风系统型材尺寸列定义
      profileSizeColumnsCf: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '型材名称',
          dataIndex: 'profileName',
          width: 120,
        },
        {
          title: '型材代码',
          dataIndex: 'profileCode',
          width: 100,
        },
        {
          title: '长度',
          dataIndex: 'length',
          width: 80,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 60,
        },
        {
          title: '类别',
          dataIndex: 'category',
          width: 80,
        },
        {
          title: '备注',
          dataIndex: 'remark',
        },
      ],

      // 新格尔系统型材尺寸列定义
      profileSizeColumnsXge: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 80,
        },
        {
          title: '型材编号',
          dataIndex: 'profileCode',
          width: 100,
        },
        {
          title: '型材名称',
          dataIndex: 'profileName',
          width: 120,
        },
        {
          title: '颜色',
          dataIndex: 'color',
          width: 80,
        },
        {
          title: '切角',
          dataIndex: 'cutAngle',
          width: 80,
        },
        {
          title: '长度',
          dataIndex: 'length',
          width: 80,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 60,
        },
      ],
    }
  },
  computed: {
    tokenHeader() {
      return {
        'X-Access-Token': Vue.ls.get(ACCESS_TOKEN),
      }
    },

    uploadAction() {
      return `${window._CONFIG['domianURL']}/sys/common/upload`
    },

    // 计算已付款总额
    totalPaidAmount() {
      if (!this.transactionRecords || this.transactionRecords.length === 0) {
        return this.model.prepayment || 0
      }

      let totalPaid = 0
      this.transactionRecords.forEach((record) => {
        if (record.amount) {
          // 如果是退款类型，则减去金额
          if (record.transactionType === '4' || record.transactionType === 4) {
            totalPaid -= parseFloat(record.amount)
          } else {
            totalPaid += parseFloat(record.amount)
          }
        }
      })

      // 确保不小于0
      return Math.max(0, totalPaid)
    },

    // 计算未付款总额
    totalUnpaidAmount() {
      const totalAmount = parseFloat(this.model.totalAmount || 0)
      const paidAmount = this.totalPaidAmount

      // 确保不小于0
      return Math.max(0, totalAmount - paidAmount)
    },

    // 计算付款状态
    paymentStatus() {
      const paidAmount = this.totalPaidAmount
      const totalAmount = parseFloat(this.model.totalAmount || 0)

      if (paidAmount <= 0) {
        return 0 // 未付款
      } else if (paidAmount >= totalAmount) {
        return 2 // 已付清
      } else {
        return 1 // 部分付款
      }
    },

    // 获取只读模式下的交易记录列显示配置
    transactionColumnsReadOnly() {
      // 返回不包含操作列的列配置
      return this.transactionColumns.filter((col) => col.dataIndex !== 'action')
    },

    // 判断是否为长风优化软件类型
    isChangfengType() {
      // 先检查当前查看的详情记录
      if (this.currentDetailRecord && this.currentDetailRecord.optimizationSoftwareType !== undefined) {
        return (
          this.currentDetailRecord.optimizationSoftwareType === '0' ||
          this.currentDetailRecord.optimizationSoftwareType === 0
        )
      }
      // 如果没有详情记录，则检查主表记录
      return this.model && (this.model.optimizationSoftwareType === '0' || this.model.optimizationSoftwareType === 0)
    },
  },
  mounted() {
    // 在组件挂载时初始化表单
    this.form = this.$form.createForm(this)
    this.detailForm = this.$form.createForm(this)
    this.totalAmountForm = this.$form.createForm(this)
    this.totalCostForm = this.$form.createForm(this)
    this.progressForm = this.$form.createForm(this)
  },
  beforeDestroy() {
    // 组件销毁前，只有在新增模式下才清除临时保存的数据
    if (!this.model.id && this.detailDataSource.length > 0 && this.detailDataSource.some((item) => item.id)) {
      this.clearTempSavedDetails()
    }
  },
  methods: {
    // 添加生成唯一ID的方法
    generateUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
          v = c == 'x' ? r : (r & 0x3) | 0x8
        return v.toString(16)
      })
    },

    // 处理Tab切换
    handleTabChange(key) {
      this.activeKey = key

      // 当切换到财务信息标签页时，重新计算利润并确保财务信息正确显示
      if (key === '2') {
        // 如果是新增模式，并且没有手动设置成本汇总，则从明细中计算
        if (!this.model.id && (!this.model.totalCost || parseFloat(this.model.totalCost) === 0)) {
          this.calculateDetailCost()
        }

        // 重新计算利润
        this.calculateProfit()

        // 确保财务信息字段正确显示
        this.$nextTick(() => {
          // 获取当前表单值
          const currentValues = this.form.getFieldsValue()

          // 检查是否有财务信息字段为空，如果为空则设置默认值
          const formValues = {
            totalAmount:
              currentValues.totalAmount !== undefined && currentValues.totalAmount !== null
                ? currentValues.totalAmount
                : this.model.totalAmount || 0,
            prepayment:
              currentValues.prepayment !== undefined && currentValues.prepayment !== null
                ? currentValues.prepayment
                : this.model.prepayment || 0,
            totalCost:
              currentValues.totalCost !== undefined && currentValues.totalCost !== null
                ? currentValues.totalCost
                : this.model.totalCost || 0,
            profit:
              currentValues.profit !== undefined && currentValues.profit !== null
                ? currentValues.profit
                : this.model.profit || 0,
            paidAmount:
              currentValues.paidAmount !== undefined && currentValues.paidAmount !== null
                ? currentValues.paidAmount
                : this.model.paidAmount || this.totalPaidAmount || 0,
            unpaidAmount:
              currentValues.unpaidAmount !== undefined && currentValues.unpaidAmount !== null
                ? currentValues.unpaidAmount
                : this.model.unpaidAmount || this.totalUnpaidAmount || 0,
            // 修复对transactionType和paymentMethod的处理，确保不会对undefined调用toString()
            transactionType:
              currentValues.transactionType ||
              (this.model.transactionType !== null && this.model.transactionType !== undefined
                ? this.model.transactionType.toString()
                : ''),
            paymentMethod:
              currentValues.paymentMethod ||
              (this.model.paymentMethod !== null && this.model.paymentMethod !== undefined
                ? this.model.paymentMethod.toString()
                : ''),
            transactionPersonId: this.model.transactionPersonId || '',
          }

          console.log('切换到财务标签页，设置表单值:', formValues)

          // 更新表单值
          this.form.setFieldsValue(formValues)

          // 更新财务表格数据
          this.updateFinanceData(formValues)

          // 如果有支付凭证，确保正确显示
          const paymentVoucher = currentValues.paymentVoucher || this.model.paymentVoucher
          if (paymentVoucher && typeof paymentVoucher === 'string') {
            // 将字符串格式的支付凭证转换为数组格式
            this.form.setFieldsValue({
              paymentVoucher: [
                {
                  name: paymentVoucher.substring(paymentVoucher.lastIndexOf('/') + 1),
                  status: 'done',
                  url: paymentVoucher,
                  response: { message: paymentVoucher, success: true },
                },
              ],
            })
          }

          // 初始化销售总额编辑模态框的表单值
          this.totalAmountForm.setFieldsValue({
            totalAmount: formValues.totalAmount,
          })

          // 初始化成本汇总编辑模态框的表单值
          this.totalCostForm.setFieldsValue({
            totalCost: formValues.totalCost,
          })

          // 延迟一点时间再次计算利润，确保数据已更新
          setTimeout(() => {
            this.calculateProfit()
          }, 100)
        })

        // 如果有订单ID，加载交易记录
        if (this.model && this.model.id) {
          this.loadTransactionRecords(this.model.id)
        }
      }
      // 当切换到进度标签页时，加载进度记录
      else if (key === '4' && this.model && this.model.id) {
        this.loadProgressList(this.model.id)
      }
    },

    // 从明细中计算成本汇总
    calculateDetailCost() {
      if (!this.detailDataSource || this.detailDataSource.length === 0) {
        return
      }

      let totalCost = 0

      this.detailDataSource.forEach((item) => {
        if (item.cost) {
          totalCost += Number(item.cost || 0)
        }
      })

      // 设置成本汇总
      this.model.totalCost = totalCost

      // 更新表单值
      this.$nextTick(() => {
        this.form.setFieldsValue({
          totalCost: totalCost,
        })
      })
    },

    // 添加兼容JeecgListMixin的add方法
    add() {
      this.show()
    },

    // 添加兼容JeecgListMixin的edit方法
    edit(record) {
      this.show(record)
    },

    // 获取父级Modal元素，用于解决日期选择器和下拉框被遮挡的问题
    getParentModal() {
      return document.body.querySelector('.ant-modal-wrap')
    },

    show(record) {
      this.visible = true

      // 如果是编辑模式(record存在)，则直接显示订单信息，否则显示导入页面
      this.activeKey = record ? '1' : '0'

      // 清空产品明细
      this.detailDataSource = []

      // 重置上传状态
      this.uploadStatus = ''
      this.uploadMessage = ''
      this.parseResult = null

      // 重置提交按钮状态
      this.disableSubmit = false

      if (record) {
        // 编辑模式
        this.model = Object.assign({}, record)
        this.title = '编辑订单'

        // 使用新接口获取订单完整信息
        this.getOrderCompleteInfo(record.id)
      } else {
        // 新增模式
        this.model = {}
        this.title = '添加订单'

        // 获取当前用户的优化软件类型，设为默认值
        this.getCurrentUserOptimizeSoftType()

        // 设置订单默认状态为新增订单-待审核(0)
        this.model.status = 0

        // 使用 $nextTick 确保表单已经渲染完成后再设置初始值
        this.$nextTick(() => {
          this.form.setFieldsValue({
            orderDate: moment(),
            status: 0,
          })
        })
      }
    },

    // 获取订单完整信息
    getOrderCompleteInfo(orderId) {
      this.confirmLoading = true
      getAction(this.url.getOrderDetailById, { id: orderId })
        .then((res) => {
          if (res.success && res.result) {
            // 设置订单基本信息
            this.model = Object.assign({}, res.result)

            // 设置产品明细
            if (res.result.productSalesOrderDetailList && res.result.productSalesOrderDetailList.length > 0) {
              this.detailDataSource = res.result.productSalesOrderDetailList
              console.log('获取到产品明细数据:', this.detailDataSource.length, '条记录')
            }

            // 加载进度记录
            this.loadProgressList(orderId)

            // 使用 $nextTick 确保表单已经渲染完成
            this.$nextTick(() => {
              // 设置表单字段值，确保处理null值
              const formValues = {
                orderNo: this.model.orderNo,
                salesPersonId: this.model.salesPersonId,
                customerId: this.model.customerId,
                projectId: this.model.projectId,
                projectArea: this.model.projectArea || '',
                optimizationSoftwareType:
                  this.model.optimizationSoftwareType !== null ? this.model.optimizationSoftwareType.toString() : '0',
                description: this.model.description || '',
                // 确保财务信息字段有默认值，避免显示为空
                totalAmount: this.model.totalAmount !== null ? this.model.totalAmount : 0,
                prepayment: this.model.prepayment !== null ? this.model.prepayment : 0,
                totalCost: this.model.totalCost !== null ? this.model.totalCost : 0,
                profit: this.model.profit !== null ? this.model.profit : 0,
                paymentVoucher: this.model.paymentVoucher,
                windowConfirmationFile: this.model.windowConfirmationFile,
                status: this.model.status !== null ? this.model.status.toString() : '0',
                // 明确处理交易类型和支付方式字段，确保不会对undefined调用toString()
                transactionType:
                  this.model.transactionType !== null && this.model.transactionType !== undefined
                    ? this.model.transactionType.toString()
                    : '',
                paymentMethod:
                  this.model.paymentMethod !== null && this.model.paymentMethod !== undefined
                    ? this.model.paymentMethod.toString()
                    : '',
                transactionPersonId: this.model.transactionPersonId || '',
              }

              // 打印财务信息，用于调试
              console.log('财务信息设置:', {
                totalAmount: this.model.totalAmount,
                prepayment: this.model.prepayment,
                totalCost: this.model.totalCost,
                profit: this.model.profit,
                transactionType: this.model.transactionType,
                paymentMethod: this.model.paymentMethod,
              })

              this.form.setFieldsValue(formValues)

              // 处理日期类型
              this.form.setFieldsValue({
                orderDate: this.model.orderDate ? moment(this.model.orderDate) : null,
                deliveryDate: this.model.deliveryDate ? moment(this.model.deliveryDate) : null,
              })

              // 更新财务表格数据
              this.updateFinanceData(formValues)

              // 编辑模式下初始计算利润
              setTimeout(() => {
                this.calculateProfit()

                // 处理支付凭证显示
                const paymentVoucher = this.model.paymentVoucher
                if (paymentVoucher) {
                  // 将字符串格式的支付凭证转换为数组格式
                  this.form.setFieldsValue({
                    paymentVoucher: [
                      {
                        name: paymentVoucher.substring(paymentVoucher.lastIndexOf('/') + 1),
                        status: 'done',
                        url: paymentVoucher,
                        response: { message: paymentVoucher, success: true },
                      },
                    ],
                  })
                }

                // 再次确认财务信息字段已正确设置
                const currentValues = this.form.getFieldsValue()
                console.log('表单当前财务信息:', {
                  totalAmount: currentValues.totalAmount,
                  prepayment: currentValues.prepayment,
                  totalCost: currentValues.totalCost,
                  profit: currentValues.profit,
                  transactionType: currentValues.transactionType,
                  paymentMethod: currentValues.paymentMethod,
                })

                // 如果财务信息字段为空，再次尝试设置
                if (currentValues.totalAmount === undefined || currentValues.totalAmount === null) {
                  this.form.setFieldsValue({ totalAmount: this.model.totalAmount || 0 })
                  this.updateFinanceDataItem('totalAmount', this.model.totalAmount || 0)
                }
                if (currentValues.prepayment === undefined || currentValues.prepayment === null) {
                  this.form.setFieldsValue({ prepayment: this.model.prepayment || 0 })
                  this.updateFinanceDataItem('prepayment', this.model.prepayment || 0)
                }
                if (currentValues.totalCost === undefined || currentValues.totalCost === null) {
                  this.form.setFieldsValue({ totalCost: this.model.totalCost || 0 })
                  this.updateFinanceDataItem('totalCost', this.model.totalCost || 0)
                }
                if (currentValues.profit === undefined || currentValues.profit === null) {
                  this.form.setFieldsValue({ profit: this.model.profit || 0 })
                  this.updateFinanceDataItem('profit', this.model.profit || 0)
                }
              }, 300)
            })
          } else {
            this.$message.error(res.message || '获取订单信息失败')
          }
          this.confirmLoading = false
        })
        .catch((err) => {
          console.error('获取订单信息出错:', err)
          this.$message.error('获取订单信息失败')
          this.confirmLoading = false
        })
    },

    // 上传前检查文件类型
    beforeUpload(file) {
      const isExcel =
        file.type === 'application/vnd.ms-excel' ||
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isExcel) {
        this.$message.error('只能上传Excel文件!')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB!')
        return false
      }

      this.uploadStatus = 'uploading'
      this.uploadMessage = '文件上传中...'
      return true
    },

    // 处理窗型确认文件上传
    handleFileUpload(info) {
      const status = info.file.status
      if (status === 'uploading') {
        this.uploadStatus = 'uploading'
        this.uploadMessage = '文件上传中...'
      } else if (status === 'done') {
        const response = info.file.response
        if (response.success) {
          // 如果之前已经上传过文件并有临时保存的数据，先删除
          if (this.detailDataSource.length > 0 && this.detailDataSource.some((item) => item.id)) {
            this.clearTempSavedDetails()
          }

          this.uploadStatus = 'success'
          this.uploadMessage = '文件解析成功'
          this.parseResult = response.result
          console.log('解析结果:', this.parseResult)

          // 处理解析结果，将数据添加到产品明细中
          if (this.parseResult && this.parseResult.details && this.parseResult.details.length > 0) {
            // 清空现有数据源
            this.detailDataSource = []

            // 将解析的数据添加到明细中
            this.parseResult.details.forEach((detail) => {
              // 为每个明细项生成唯一key
              detail.key = detail.id || this.generateUUID()

              // 保留原始photoUrl，不做修改
              if (detail.photoUrl) {
                console.log('原始图纸URL:', detail.photoUrl)
              }

              this.detailDataSource.push(detail)
            })

            // 提示用户点击"下一步"按钮继续
            this.$message.success('文件解析成功，请点击"下一步"按钮继续')

            // 如果有优化软件类型，自动设置表单值
            if (this.parseResult.optimizeSoftwareType !== undefined) {
              this.form.setFieldsValue({
                optimizationSoftwareType: this.parseResult.optimizeSoftwareType.toString(),
              })
            }

            // 设置财务信息（门确认单专用）
            if (this.parseResult.totalAmount !== undefined) {
              this.model.totalAmount = this.parseResult.totalAmount
              console.log('设置销售总价:', this.parseResult.totalAmount)
            }
            if (this.parseResult.receivedAmount !== undefined) {
              this.model.receivedAmount = this.parseResult.receivedAmount
              console.log('设置实收金额:', this.parseResult.receivedAmount)
            }
            if (this.parseResult.unpaidAmount !== undefined) {
              this.model.unpaidAmount = this.parseResult.unpaidAmount
              console.log('设置未收款金额:', this.parseResult.unpaidAmount)
            }

            // 处理订单编号 - 直接从接口返回的orderNo字段获取
            if (this.parseResult.orderNo) {
              this.$nextTick(() => {
                this.form.setFieldsValue({ orderNo: this.parseResult.orderNo })
                this.model.orderNo = this.parseResult.orderNo // 同时设置model对象的值
                console.log('设置订单编号:', this.parseResult.orderNo)
              })
            } else if (this.parseResult.orderId) {
              // 兼容旧版本API，使用orderId字段
              this.$nextTick(() => {
                this.form.setFieldsValue({ orderNo: this.parseResult.orderId })
                this.model.orderNo = this.parseResult.orderId // 同时设置model对象的值
                console.log('使用orderId设置订单编号:', this.parseResult.orderId)
              })
            }

            // 处理日期 - 使用多种格式尝试解析日期
            const parseDate = (dateStr) => {
              if (!dateStr) return null

              // 尝试不同的日期格式
              const formats = ['YYYY/MM/DD', 'YYYY-MM-DD', 'DD/MM/YYYY', 'MM/DD/YYYY']

              for (const format of formats) {
                const date = moment(dateStr, format)
                if (date.isValid()) {
                  return date
                }
              }

              // 尝试自动解析
              const date = moment(dateStr)
              return date.isValid() ? date : null
            }

            // 设置下单日期
            if (this.parseResult.orderDate) {
              const orderDate = parseDate(this.parseResult.orderDate)
              if (orderDate) {
                console.log('设置下单日期:', orderDate.format('YYYY-MM-DD'))
                this.form.setFieldsValue({ orderDate: orderDate })
              }
            }

            // 设置交付日期
            if (this.parseResult.deliveryDate) {
              const deliveryDate = parseDate(this.parseResult.deliveryDate)
              if (deliveryDate) {
                console.log('设置交付日期:', deliveryDate.format('YYYY-MM-DD'))
                this.form.setFieldsValue({ deliveryDate: deliveryDate })
              }
            }

            // 计算并设置总金额，但不自动切换标签页
            this.calculateAndSetTotalAmount(false)
          }
        } else {
          this.uploadStatus = 'error'
          this.uploadMessage = response.message || '文件解析失败'
          this.parseResult = null
        }
      } else if (status === 'error') {
        this.uploadStatus = 'error'
        this.uploadMessage = '文件上传失败'
        this.parseResult = null
      }
    },

    // 计算并设置总金额
    calculateAndSetTotalAmount(autoSwitchTab = true) {
      if (!this.detailDataSource || this.detailDataSource.length === 0) {
        return
      }

      let totalCost = 0

      this.detailDataSource.forEach((item) => {
        if (item.cost) {
          totalCost += Number(item.cost || 0)
        }
      })

      // 设置表单值
      this.$nextTick(() => {
        this.form.setFieldsValue({
          totalCost: totalCost,
        })

        // 重新计算利润
        this.calculateProfit()

        // 如果在编辑模式下且需要自动切换标签页，则切换到财务信息标签页
        // 注意：我们移除了自动切换逻辑，由用户手动切换标签页
      })
    },

    generateOrderNo() {
      getAction(this.url.generateOrderNo).then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              orderNo: res.result,
            })
          })
        }
      })
    },

    getCurrentUserOptimizeSoftType() {
      // 使用不需要empId参数的接口
      getAction('/sys/employee/getCurrentOptimizeSoftType').then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              optimizationSoftwareType: res.result,
            })
          })
        }
      })
    },

    /**
    新增订单-待审核	0	
    审核通过-待上传	1	
    已上传汇总单-待上传优化单	2	
    已上传优化单-待提交审核	3	
    待下发	4	
    领料单待审核	5	
    待领料	6	
    生产中	7	
    已完成	8	
    已驳回	9
    */
    // 获取进度类型对应的颜色
    getProgressColor(progressType, isLatest = false) {
      // 如果是最新状态，使用蓝色系
      if (isLatest) {
        switch (parseInt(progressType)) {
          case 0:
            return '#1890ff' // 新增订单-待审核
          case 1:
            return '#2f54eb' // 审核通过-待上传
          case 2:
            return '#1890ff' // 已上传汇总单-待上传优化单
          case 3:
            return '#1890ff' // 已上传优化单-待提交审核
          case 4:
            return '#1890ff' // 待下发
          case 5:
            return '#1890ff' // 领料单待审核
          case 6:
            return '#1890ff' // 待领料
          case 7:
            return '#1890ff' // 生产中
          case 8:
            return '#1890ff' // 已完成
          case 9:
            return '#1890ff' // 已驳回
          default:
            return 'blue' // 其他类型
        }
      }
      // 其余状态使用绿色系
      else {
        switch (parseInt(progressType)) {
          case 0:
            return '#52c41a' // 新增订单-待审核
          case 1:
            return '#52c41a' // 审核通过-待上传
          case 2:
            return '#52c41a' // 已上传汇总单-待上传优化单
          case 3:
            return '#52c41a' // 已上传优化单-待提交审核
          case 4:
            return '#52c41a' // 待下发
          case 5:
            return '#52c41a' // 领料单待审核
          case 6:
            return '#52c41a' // 待领料
          case 7:
            return '#52c41a' // 生产中
          case 8:
            return '#52c41a' // 已完成
          case 9:
            return '#52c41a' // 已驳回
          default:
            return 'gray' // 其他类型
        }
      }
    },
    /**
    新增订单-待审核	0	
    审核通过-待上传	1	
    已上传汇总单-待上传优化单	2	
    已上传优化单-待提交审核	3	
    待下发	4	
    领料单待审核	5	
    待领料	6	
    生产中	7	
    已完成	8	
    已驳回	9
    */
    // 获取进度类型对应的文本
    getProgressTypeText(progressType) {
      // 根据进度类型返回对应的文本描述
      switch (parseInt(progressType)) {
        case 0:
          return '新增订单-待审核'
        case 1:
          return '审核通过-待上传'
        case 2:
          return '已上传汇总单-待上传优化单'
        case 3:
          return '已上传优化单-待提交审核'
        case 4:
          return '待下发'
        case 5:
          return '领料单待审核'
        case 6:
          return '待领料'
        case 7:
          return '生产中'
        case 8:
          return '已完成'
        case 9:
          return '已驳回'
        default:
          return '其他'
      }
    },

    getOrderDetails(orderId) {
      getAction(`/oms/productSalesOrder/detail/list?orderId=${orderId}`).then((res) => {
        if (res.success) {
          this.detailDataSource = res.result || []
          console.log('获取到产品明细数据:', this.detailDataSource.length, '条记录')

          // 计算并更新总成本，但不自动切换标签页
          this.calculateAndSetTotalAmount(false)
        } else {
          this.$message.error('获取产品明细失败: ' + res.message)
        }
      })

      // 获取订单相关的交易记录
      this.loadTransactionRecords(orderId)
    },

    handleOk() {
      // 如果禁用提交，则不执行提交操作
      if (this.disableSubmit) {
        this.handleCancel()
        return
      }

      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          // 检查产品明细是否为空
          if (this.detailDataSource.length === 0) {
            this.$message.warning('请至少添加一个产品明细')
            this.activeKey = '3'
            return
          }

          this.confirmLoading = true

          // 处理日期格式
          values.orderDate = values.orderDate ? values.orderDate.format('YYYY-MM-DD') : null
          values.deliveryDate = values.deliveryDate ? values.deliveryDate.format('YYYY-MM-DD') : null

          // 处理支付凭证字段
          if (values.paymentVoucher) {
            // 如果是数组格式，转换为字符串
            if (Array.isArray(values.paymentVoucher)) {
              if (values.paymentVoucher.length > 0) {
                // 获取第一个文件的URL
                const firstFile = values.paymentVoucher[0]
                if (firstFile.url) {
                  values.paymentVoucher = firstFile.url
                } else if (firstFile.response && firstFile.response.message) {
                  values.paymentVoucher = firstFile.response.message
                }
              } else {
                values.paymentVoucher = null
              }
            }
          }

          // 处理交易类型和支付方式，确保是整数类型
          if (values.transactionType) {
            values.transactionType = parseInt(values.transactionType)
          }

          if (values.paymentMethod) {
            values.paymentMethod = parseInt(values.paymentMethod)
          }

          // 确保金额字段为数字类型
          values.totalAmount = parseFloat(this.model.totalAmount || 0)
          values.totalCost = parseFloat(this.model.totalCost || 0)
          values.profit = this.calculateProfit()
          values.prepayment = parseFloat(values.prepayment || 0)
          values.paidAmount = parseFloat(this.totalPaidAmount || 0)
          values.unpaidAmount = parseFloat(this.totalUnpaidAmount || 0)

          // 组装提交数据
          let formData = Object.assign({}, this.model, values)
          formData.productSalesOrderDetailList = this.detailDataSource

          // 处理交易记录数据
          // 首先检查表格中的交易记录
          if (this.transactionRecords && this.transactionRecords.length > 0) {
            // 过滤出非编辑状态的有效交易记录
            const validTransactions = this.transactionRecords.filter((record) => !record.editable)
            if (validTransactions.length > 0) {
              // 转换为后端需要的格式
              formData.transactionList = validTransactions.map((record) => ({
                id: record.id, // 如果是已有记录，包含ID
                transactionType: record.transactionType ? parseInt(record.transactionType) : 1,
                paymentMethod: record.paymentMethod ? parseInt(record.paymentMethod) : 1,
                amount: parseFloat(record.amount || 0),
                description:
                  record.description ||
                  this.getTransactionDescription(record.transactionType ? parseInt(record.transactionType) : 1),
                transactionPersonId: record.transactionPersonId,
                transactionVoucher: record.paymentVoucher || record.transactionVoucher,
                transactionTime: record.transactionTime || moment().format('YYYY-MM-DD HH:mm:ss'),
              }))

              console.log('提交的交易记录列表:', formData.transactionList.length, '条')
            }
          }
          // 如果没有表格中的交易记录，但有预付款，则创建单个交易记录
          else if (values.prepayment > 0 && values.paymentVoucher) {
            // 准备单个交易记录
            this.prepareTransactionData(values.prepayment, values.paymentVoucher)

            // 将单个交易记录添加到提交数据中
            if (this.model.transaction) {
              console.log('提交单个交易记录:', this.model.transaction)
              formData.transaction = this.model.transaction
            }
          }

          let url = this.model.id ? this.url.edit : this.url.add

          // 提交表单
          if (this.model.id) {
            // 编辑模式使用putAction
            putAction(url, formData)
              .then((res) => {
                if (res.success) {
                  this.$message.success(res.message)

                  this.$emit('ok')
                  this.visible = false
                } else {
                  this.$message.warning(res.message)
                }
              })
              .finally(() => {
                this.confirmLoading = false
              })
          } else {
            // 新增模式使用postAction
            postAction(url, formData)
              .then((res) => {
                if (res.success) {
                  this.$message.success(res.message)
                  this.$emit('ok')
                  this.visible = false
                } else {
                  this.$message.warning(res.message)
                }
              })
              .finally(() => {
                this.confirmLoading = false
              })
          }
        } else {
          // 表单验证失败
          this.$message.warning('请完善表单信息')
        }
      })
    },

    handleCancel() {
      // 只有在新增模式下且有临时保存的数据时，才删除临时数据
      if (!this.model.id && this.detailDataSource.length > 0 && this.detailDataSource.some((item) => item.id)) {
        this.clearTempSavedDetails()
      }

      // 清空交易记录数据，避免下次新增时显示上一次的数据
      this.transactionRecords = []
      this.tempTransactionRecords = []

      this.visible = false
    },

    // 添加产品明细
    handleAddDetail() {
      this.$refs.detailModal = this.$dialog.open({
        title: '添加产品明细',
        width: '80%',
        content: (h) => {
          return h(ProductDetailModal, {
            props: {
              mode: 'add',
            },
            on: {
              submit: (detail) => {
                // 为明细生成唯一ID
                detail.key = this.generateUUID()
                this.detailDataSource.push(detail)
                this.$refs.detailModal.destroy()
                this.$message.success('添加产品明细成功')

                // 更新总金额和成本
                this.calculateAndSetTotalAmount()

                // 如果是新增模式，自动更新成本汇总
                if (!this.model.id) {
                  this.calculateDetailCost()
                  this.calculateProfit()
                }
              },
            },
          })
        },
      })
    },

    // 编辑产品明细
    handleEditDetail(record, index) {
      this.$refs.detailModal = this.$dialog.open({
        title: '编辑产品明细',
        width: '80%',
        content: (h) => {
          return h(ProductDetailModal, {
            props: {
              mode: 'edit',
              detail: JSON.parse(JSON.stringify(record)),
            },
            on: {
              submit: (detail) => {
                // 保持原有的key
                detail.key = record.key
                this.$set(this.detailDataSource, index, detail)
                this.$refs.detailModal.destroy()
                this.$message.success('编辑产品明细成功')

                // 更新总金额和成本
                this.calculateAndSetTotalAmount()

                // 如果是新增模式，自动更新成本汇总
                if (!this.model.id) {
                  this.calculateDetailCost()
                  this.calculateProfit()
                }
              },
            },
          })
        },
      })
    },

    // 删除产品明细
    handleRemoveDetail(record, index) {
      this.detailDataSource.splice(index, 1)
      this.$message.success('删除产品明细成功')

      // 更新总金额和成本
      this.calculateAndSetTotalAmount()

      // 如果是新增模式，自动更新成本汇总
      if (!this.model.id) {
        this.calculateDetailCost()
        this.calculateProfit()
      }
    },

    // 清除临时保存的明细数据
    clearTempSavedDetails() {
      const detailIds = this.detailDataSource
        .filter((item) => item.id) // 只处理有id的记录
        .map((item) => item.id)

      if (detailIds.length > 0) {
        // 调用接口删除临时保存的数据
        postAction('/oms/productSalesOrder/detail/batchDelete', { detailIds: detailIds })
          .then((res) => {
            if (res.success) {
              console.log('临时数据清除成功')
            } else {
              console.error('临时数据清除失败:', res.message)
            }
          })
          .catch((err) => {
            console.error('临时数据清除异常:', err)
          })
      }
    },

    // 选择客户
    handleSelectCustomer() {
      this.$refs.customerModal.add()
      this.$refs.customerModal.title = '选择客户'
    },

    // 客户选择回调
    handleCustomerSelected(selectedCustomer) {
      if (selectedCustomer) {
        this.customerId = selectedCustomer.id
        this.form.setFieldsValue({
          customerName: selectedCustomer.customerName,
        })

        // 清空已选择的工程
        this.form.setFieldsValue({
          projectId: '',
          projectName: '',
          projectArea: '',
        })
      }
    },

    // 选择工程
    handleSelectProject() {
      const customerId = this.form.getFieldValue('customerId')
      if (!customerId) {
        this.$message.warning('请先选择客户')
        return
      }

      this.$refs.projectSelectModal.show(customerId)
    },

    // 工程选择回调
    handleProjectSelected(selectedProject) {
      if (selectedProject) {
        this.form.setFieldsValue({
          projectId: selectedProject.id,
          projectName: selectedProject.projectName,
          projectArea: selectedProject.projectArea || '',
        })
      }
    },

    // 产品明细模态框确认按钮
    handleDetailOk() {
      this.detailForm.validateFields((err, values) => {
        if (err) {
          return
        }

        // 如果是编辑模式
        if (this.detailIndex !== -1) {
          // 更新现有记录
          this.$set(this.detailDataSource, this.detailIndex, {
            ...this.detailDataSource[this.detailIndex],
            ...values,
            key: this.detailDataSource[this.detailIndex].key || this.generateUUID(),
          })
        } else {
          // 添加新记录
          this.detailDataSource.push({
            ...values,
            key: this.generateUUID(),
          })
        }

        // 关闭模态框
        this.detailVisible = false

        // 重置表单
        this.detailForm.resetFields()

        // 重置索引
        this.detailIndex = -1

        // 更新总金额
        this.calculateAndSetTotalAmount()
      })
    },

    // 产品明细模态框取消按钮
    handleDetailCancel() {
      this.detailVisible = false
      this.detailForm.resetFields()
      this.detailIndex = -1
    },

    // 添加客户变更处理方法
    onCustomerChange(customerId, customerInfo) {
      if (customerInfo) {
        this.customerId = customerId
        this.form.setFieldsValue({
          customerName: customerInfo.customerName,
        })

        // 清空已选择的工程
        this.form.setFieldsValue({
          projectId: '',
          projectName: '',
          projectArea: '',
        })
      }
    },

    // 添加工程变更处理方法
    onProjectChange(projectId, projectInfo) {
      if (projectInfo) {
        this.form.setFieldsValue({
          projectName: projectInfo.projectName,
          projectArea: projectInfo.projectArea || '',
        })
      }
    },

    // 图纸预览方法
    previewDrawing(drawingFile, record) {
      if (!drawingFile) {
        this.$message.warning('无图纸可预览')
        return
      }

      console.log('预览图纸文件:', drawingFile)
      if (record) {
        console.log('窗号:', record.windowNo, '系列:', record.windowSeries)
      }

      // 获取完整的图片URL
      this.currentDrawingUrl = this.getFullImageUrl(drawingFile)
      console.log('预览图纸完整URL:', this.currentDrawingUrl)

      if (this.currentDrawingUrl) {
        // 如果是PDF或其他非图片文件，使用kkFileView预览
        if (!this.isImageFile(drawingFile)) {
          // 使用window.open打开预览页面
          const previewUrl = this.getPreviewUrl(drawingFile)
          window.open(previewUrl, '_blank')
          return
        }

        // 图片文件在模态框中显示
        this.drawingPreviewVisible = true
      } else {
        this.$message.warning('无法预览图纸，文件可能已损坏或不存在')
      }
    },

    // 关闭图纸预览
    closeDrawingPreview() {
      this.drawingPreviewVisible = false
      this.currentDrawingUrl = ''
    },

    // 检查是否为图片文件
    isImageFile(url) {
      if (!url) return false
      return /\.(jpg|jpeg|png|gif|bmp)$/i.test(url)
    },

    // 处理图纸上传变化
    handleDrawingChange(info) {
      console.log('图纸上传信息:', info)
    },

    // 获取预览URL
    getPreviewUrl(url) {
      if (!url) return ''

      // 如果是图片文件，直接返回完整URL
      if (this.isImageFile(url)) {
        return this.getFullImageUrl(url)
      }

      // 获取完整URL
      const fullUrl = this.getFullImageUrl(url)

      // 使用kkfileview预览非图片文件
      // 从环境变量或配置中获取预览服务器地址
      let previewBaseUrl = process.env.VUE_APP_ONLINE_BASE_URL || 'http://fileview.jeecg.com/onlinePreview'

      // 确保预览URL不以/结尾
      if (previewBaseUrl.endsWith('/')) {
        previewBaseUrl = previewBaseUrl.substring(0, previewBaseUrl.length - 1)
      }

      console.log('文件预览URL:', `${previewBaseUrl}?url=${encodeURIComponent(fullUrl)}`)
      return `${previewBaseUrl}?url=${encodeURIComponent(fullUrl)}`
    },

    // 添加获取完整图片路径的方法
    getFullImageUrl(url) {
      if (!url) return ''

      console.log('处理图片URL:', url)

      try {
        // 使用jeecg标准的文件访问方式
        const fullUrl = getFileAccessHttpUrl(url)
        console.log('完整图片URL:', fullUrl)
        return fullUrl
      } catch (error) {
        console.error('获取文件URL失败:', error)
        return ''
      }
    },

    // 处理图片加载错误
    handleImageError(e) {
      console.error('图片加载失败:', e)
      // 替换为默认的无图片图标
      e.target.style.display = 'none'
      const container = e.target.parentNode
      if (container) {
        // 添加一个图标表示图片加载失败
        const icon = document.createElement('i')
        icon.className = 'anticon anticon-picture'
        icon.style.fontSize = '24px'
        icon.style.color = '#d9d9d9'
        container.insertBefore(icon, e.target)

        // 添加错误提示文本
        const errorText = document.createElement('div')
        errorText.innerText = '图片不存在'
        errorText.style.color = '#ff4d4f'
        errorText.style.fontSize = '12px'
        errorText.style.marginTop = '4px'
        container.appendChild(errorText)
      }

      this.$message.warning('图片加载失败，可能已被删除或损坏')
    },

    // 添加重置表单日期字段的方法
    resetFormDate(fieldName, date) {
      if (!date || !fieldName) return

      // 如果date不是moment对象，则直接设置值
      if (typeof date !== 'object' || !date.isValid) {
        this.$nextTick(() => {
          this.form.setFieldsValue({ [fieldName]: date })
          console.log(`设置${fieldName}成功:`, date)
        })
        return
      }

      // 确保日期对象有效
      if (!date.isValid()) {
        console.warn(`无效的日期对象: ${fieldName}`)
        return
      }

      // 强制重置表单中的日期字段
      this.$nextTick(() => {
        try {
          // 先清空原值
          this.form.setFieldsValue({ [fieldName]: null })

          // 再设置新值
          setTimeout(() => {
            this.form.setFieldsValue({ [fieldName]: date })
            console.log(`重置${fieldName}成功:`, date.format('YYYY-MM-DD'))
          }, 100)
        } catch (error) {
          console.error(`重置${fieldName}失败:`, error)
        }
      })
    },

    // 添加计算销售利润的方法
    calculateProfit() {
      // 获取销售总额和成本汇总
      const totalAmount = parseFloat(this.model.totalAmount || 0)
      const totalCost = parseFloat(this.model.totalCost || 0)

      // 计算销售利润 = 销售总额 - 成本汇总
      const profit = totalAmount - totalCost

      // 更新利润字段
      if (this.form) {
        this.form.setFieldsValue({
          profit: profit,
        })
        this.model.profit = profit
      }

      return profit
    },

    // 添加处理文件下载的方法
    handleFileDownload(file) {
      if (!file.url) {
        this.$message.warning('文件链接不存在')
        return
      }

      // 如果是图片文件，使用预览功能
      if (this.isImageFile(file.url)) {
        this.previewDrawing(file.url)
      } else {
        // 非图片文件，使用浏览器下载
        window.open(this.getPreviewUrl(file.url), '_blank')
      }
    },

    // 修改onPrepaymentBlur方法，处理预付款变更
    onPrepaymentBlur() {
      const prepayment = this.form.getFieldValue('prepayment') || 0
      const totalAmount = this.form.getFieldValue('totalAmount') || 0

      // 如果有预付款，提示用户上传支付凭证
      if (prepayment > 0) {
        // 获取当前支付凭证
        const paymentVoucher = this.form.getFieldValue('paymentVoucher')
        if (!paymentVoucher || (Array.isArray(paymentVoucher) && paymentVoucher.length === 0)) {
          this.$message.info('请上传支付凭证以记录预付款信息')
        }

        // 设置交易类型和支付方式默认值
        const transactionType = this.form.getFieldValue('transactionType')
        const paymentMethod = this.form.getFieldValue('paymentMethod')

        if (!transactionType) {
          // 预付款 - 默认值1
          this.form.setFieldsValue({ transactionType: '1' })
          this.updateFinanceDataItem('transactionType', '1')
        }

        if (!paymentMethod) {
          // 现金 - 默认值1
          this.form.setFieldsValue({ paymentMethod: '1' })
          this.updateFinanceDataItem('paymentMethod', '1')
        }

        // 准备交易记录数据
        this.prepareTransactionData(prepayment)
      }

      // 计算付款状态
      if (prepayment <= 0) {
        this.paymentStatus = 0 // 未付款
      } else if (prepayment >= totalAmount) {
        this.paymentStatus = 2 // 已付款
      } else {
        this.paymentStatus = 1 // 部分付款
      }
    },

    // 添加准备交易记录数据的方法
    prepareTransactionData(amount, voucherUrl) {
      const transactionType = this.form.getFieldValue('transactionType') || '1'
      const paymentMethod = this.form.getFieldValue('paymentMethod') || '1'
      const transactionPersonId =
        this.form.getFieldValue('transactionPersonId') || this.form.getFieldValue('salesPersonId')

      // 获取当前用户
      const currentUser = this.$store.getters.userInfo

      // 设置交易记录数据
      this.model.transaction = {
        transactionType: transactionType ? parseInt(transactionType) : 1,
        paymentMethod: paymentMethod ? parseInt(paymentMethod) : 1,
        amount: parseFloat(amount || 0),
        description: this.getTransactionDescription(transactionType ? parseInt(transactionType) : 1),
        transactionPersonId: transactionPersonId || (currentUser ? currentUser.id : ''),
        transactionTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      }

      // 处理凭证URL
      if (voucherUrl) {
        // 如果直接传入了URL字符串
        this.model.transaction.transactionVoucher = voucherUrl
      } else {
        // 尝试从表单获取
        const paymentVoucher = this.form.getFieldValue('paymentVoucher')
        if (paymentVoucher && Array.isArray(paymentVoucher) && paymentVoucher.length > 0) {
          const fileInfo = paymentVoucher[0]
          if (fileInfo && fileInfo.response && fileInfo.response.message) {
            this.model.transaction.transactionVoucher = fileInfo.response.message
          } else if (fileInfo && fileInfo.url) {
            this.model.transaction.transactionVoucher = fileInfo.url
          }
        }
      }

      // 如果有已存在的订单ID，则设置orderId
      if (this.model.id) {
        this.model.transaction.orderId = this.model.id
      }

      console.log('准备交易记录数据:', this.model.transaction)
    },

    // 添加获取交易描述的方法
    getTransactionDescription(transactionType) {
      // 根据交易类型返回对应的描述
      switch (transactionType) {
        case 1:
          return '预付款'
        case 2:
          return '尾款'
        case 3:
          return '全额付款'
        case 4:
          return '退款'
        default:
          return '其他交易'
      }
    },

    // 修改handleFinanceChange方法，处理财务字段变更
    handleFinanceChange(field, value) {
      // 设置表单字段值
      this.form.setFieldsValue({ [field]: value })

      // 更新财务表格中对应项的值
      this.updateFinanceDataItem(field, value)

      // 如果改变的是交易类型或支付方式，更新交易记录数据
      if (['transactionType', 'paymentMethod', 'transactionPersonId'].includes(field)) {
        const prepayment = this.form.getFieldValue('prepayment') || 0
        if (prepayment > 0) {
          this.prepareTransactionData(prepayment)
        }
      }

      // 如果改变的是影响利润计算的字段，则重新计算利润
      if (['totalAmount', 'totalCost'].includes(field)) {
        this.calculateProfit()
      }

      // 如果改变的是预付款字段，则可能需要触发onPrepaymentBlur
      if (field === 'prepayment') {
        // 延迟一点时间确保值已更新
        setTimeout(() => {
          this.onPrepaymentBlur()
        }, 100)
      }
    },

    // 更新整个财务表格数据
    updateFinanceData(formValues) {
      // 复制一份财务数据以避免直接修改原数组
      const updatedData = [...this.financeData]

      // 更新每个财务项的值
      updatedData.forEach((item) => {
        if (formValues[item.key] !== undefined) {
          item.value = formValues[item.key]
        }
      })

      // 更新财务表格数据
      this.financeData = updatedData
    },

    // 更新财务表格中指定项的值
    updateFinanceDataItem(field, value) {
      // 查找对应的财务项
      const index = this.financeData.findIndex((item) => item.key === field)
      if (index !== -1) {
        // 复制一份财务数据以避免直接修改原数组
        const updatedData = [...this.financeData]
        // 更新指定项的值
        updatedData[index].value = value
        // 更新财务表格数据
        this.financeData = updatedData
      }
    },

    // 加载交易记录
    loadTransactionRecords(orderId) {
      if (!orderId) return

      console.log('加载订单交易记录，订单ID:', orderId)

      // 调用API获取交易记录
      getAction('/oms/productSalesOrder/transaction/list', { orderId: orderId })
        .then((res) => {
          if (res.success && res.result) {
            console.log('获取到交易记录:', res.result)

            // API返回的是分页对象，实际数据在result.records中
            const records = res.result.records || []

            // 将每条记录标记为不可编辑状态，保留后台返回的dictText转换
            const formattedRecords = records.map((item) => {
              console.log('交易记录项:', item)
              // 确保凭证字段存在
              if (item.transactionVoucher) {
                console.log('交易凭证:', item.transactionVoucher)
              }
              return {
                ...item,
                key: item.id || this.generateUUID(), // 确保每条记录有唯一的key
                transactionType:
                  item.transactionType !== null && item.transactionType !== undefined
                    ? item.transactionType.toString()
                    : '',
                paymentMethod:
                  item.paymentMethod !== null && item.paymentMethod !== undefined ? item.paymentMethod.toString() : '',
                amount: item.amount || 0, // 确保金额字段存在
                editable: false,
              }
            })

            this.transactionRecords = formattedRecords
          } else {
            console.log('没有获取到交易记录或请求失败')
            this.transactionRecords = []
          }
        })
        .catch((err) => {
          console.error('获取交易记录出错:', err)
          this.transactionRecords = []
        })
    },

    // 更新总付款金额
    updateTotalPaymentAmount() {
      if (!this.transactionRecords || this.transactionRecords.length === 0) {
        // 如果没有交易记录，总付款金额为0
        this.totalPaidAmount = 0
        this.totalUnpaidAmount = parseFloat(this.form.getFieldValue('totalAmount') || 0)
        return
      }

      // 计算总付款金额
      let totalPaid = 0
      this.transactionRecords.forEach((record) => {
        if (record.amount) {
          // 如果是退款类型，则减去金额
          if (record.transactionType === '4' || record.transactionType === 4) {
            totalPaid -= parseFloat(record.amount)
          } else {
            totalPaid += parseFloat(record.amount)
          }
        }
      })

      // 确保不小于0
      totalPaid = Math.max(0, totalPaid)

      // 更新总付款金额
      this.totalPaidAmount = totalPaid

      // 计算未付款金额
      const totalAmount = parseFloat(this.form.getFieldValue('totalAmount') || 0)
      this.totalUnpaidAmount = Math.max(0, totalAmount - totalPaid)

      console.log('更新付款金额:', {
        totalPaid: this.totalPaidAmount,
        totalUnpaid: this.totalUnpaidAmount,
        totalAmount: totalAmount,
      })
    },

    // 预览交易凭证
    previewVoucher(url) {
      if (!url) return

      console.log('预览凭证URL:', url)

      // 获取完整的URL
      const fullUrl = this.getFullImageUrl(url)
      console.log('完整凭证URL:', fullUrl)

      // 判断文件类型
      const lowerUrl = url.toLowerCase()
      if (
        lowerUrl.endsWith('.jpg') ||
        lowerUrl.endsWith('.jpeg') ||
        lowerUrl.endsWith('.png') ||
        lowerUrl.endsWith('.gif')
      ) {
        // 图片类型，使用内置预览
        this.currentDrawingUrl = fullUrl
        this.drawingPreviewVisible = true
      } else if (lowerUrl.endsWith('.pdf')) {
        // PDF类型，打开新窗口
        window.open(this.getPreviewUrl(url), '_blank')
      } else {
        // 其他类型，直接下载
        window.open(fullUrl, '_blank')
      }
    },

    // 处理支付凭证变更
    handlePaymentVoucherChange(info) {
      if (info.file.status === 'done') {
        // 文件上传成功
        if (info.file.response && info.file.response.success) {
          this.$message.success('支付凭证上传成功!')
        } else {
          this.$message.error('支付凭证上传失败: ' + (info.file.response.message || '未知错误'))
        }
      } else if (info.file.status === 'error') {
        this.$message.error('支付凭证上传失败: ' + info.file.response.message || '未知错误')
      }
    },

    // 添加交易记录编辑相关方法
    handleAddTransaction() {
      const currentUser = this.$store.getters.userInfo

      // 获取当前登录用户的员工信息
      getAction('/sys/employee/queryById', { id: currentUser.id })
        .then((res) => {
          let employeeInfo = null
          if (res.success && res.result) {
            employeeInfo = res.result
          }

          const newTransaction = {
            key: this.generateUUID(), // 使用自定义方法生成UUID
            orderId: this.model.id, // 添加orderId字段
            orderNo: this.model.orderNo, // 添加orderNo字段
            transactionType: '1',
            paymentMethod: '1',
            amount: 0,
            description: '预付款',
            transactionPersonId: employeeInfo ? employeeInfo.id : '',
            transactionPersonName: employeeInfo ? employeeInfo.empName : currentUser ? currentUser.realname : '',
            transactionTime: moment().format('YYYY-MM-DD HH:mm:ss'), // 添加交易时间
            editable: true,
            isNew: true,
          }

          // 如果是新增订单模式（没有订单ID），则添加到临时交易记录数组
          if (!this.model.id) {
            this.transactionRecords = [newTransaction, ...this.transactionRecords]
            this.tempTransactionRecords = [...this.transactionRecords] // 保存到临时数组
            this.editingTransaction = newTransaction.key
          } else {
            // 编辑模式，直接添加到交易记录数组
            this.transactionRecords = [newTransaction, ...this.transactionRecords]
            this.editingTransaction = newTransaction.key
          }
        })
        .catch((err) => {
          console.error('获取员工信息失败:', err)

          // 如果获取员工信息失败，使用用户信息
          const newTransaction = {
            key: this.generateUUID(),
            orderId: this.model.id,
            orderNo: this.model.orderNo,
            transactionType: '1',
            paymentMethod: '1',
            amount: 0,
            description: '预付款',
            transactionPersonId: currentUser ? currentUser.id : '',
            transactionPersonName: currentUser ? currentUser.realname : '',
            transactionTime: moment().format('YYYY-MM-DD HH:mm:ss'),
            editable: true,
            isNew: true,
          }

          // 如果是新增订单模式（没有订单ID），则添加到临时交易记录数组
          if (!this.model.id) {
            this.transactionRecords = [newTransaction, ...this.transactionRecords]
            this.tempTransactionRecords = [...this.transactionRecords] // 保存到临时数组
            this.editingTransaction = newTransaction.key
          } else {
            // 编辑模式，直接添加到交易记录数组
            this.transactionRecords = [newTransaction, ...this.transactionRecords]
            this.editingTransaction = newTransaction.key
          }
        })
    },

    editTransaction(record, index) {
      // 保存原始数据，用于取消编辑时恢复
      this.tempTransaction = { ...record }

      // 标记为可编辑状态
      this.$set(this.transactionRecords[index], 'editable', true)
      this.editingTransaction = record.id || record.key
    },

    saveTransaction(record, index) {
      // 验证必填字段
      if (!record.transactionType) {
        this.$message.warning('请选择交易类型')
        return
      }

      if (!record.paymentMethod) {
        this.$message.warning('请选择支付方式')
        return
      }

      if (!record.amount || record.amount <= 0) {
        this.$message.warning('请输入有效的交易金额')
        return
      }

      // 如果是新记录，则调用添加接口
      if (record.isNew) {
        // 准备添加的数据
        const transactionData = {
          productSalesOrderId: this.model.id, // 保持原字段名，后端会处理
          orderId: this.model.id, // 同时提供orderId字段以适配后端
          transactionType: record.transactionType ? parseInt(record.transactionType) : 1,
          paymentMethod: record.paymentMethod ? parseInt(record.paymentMethod) : 1,
          amount: parseFloat(record.amount),
          description:
            record.description ||
            this.getTransactionDescription(record.transactionType ? parseInt(record.transactionType) : 1),
          transactionPersonId: record.transactionPersonId,
          transactionVoucher: record.paymentVoucher || record.transactionVoucher, // 使用paymentVoucher或transactionVoucher
        }

        // 如果是编辑状态下的新记录，直接保存到交易记录数组中
        if (!this.model.id) {
          // 切换为不可编辑状态
          this.$set(this.transactionRecords[index], 'editable', false)
          this.editingTransaction = null

          // 如果是新预付款，更新表单中的预付款金额
          if (record.transactionType && parseInt(record.transactionType) === 1) {
            const currentPrepayment = parseFloat(this.form.getFieldValue('prepayment') || 0)
            const newPrepayment = currentPrepayment + parseFloat(record.amount)
            this.form.setFieldsValue({ prepayment: newPrepayment })
            this.updateFinanceDataItem('prepayment', newPrepayment)
          }

          // 更新临时交易记录数组
          this.tempTransactionRecords = [...this.transactionRecords]

          // 更新模型中的已付款和待付款金额
          this.$nextTick(() => {
            // 更新表单中的已付款和待付款字段
            this.form.setFieldsValue({
              paidAmount: this.totalPaidAmount,
              unpaidAmount: this.totalUnpaidAmount,
            })

            // 同时更新模型对象
            this.model.paidAmount = this.totalPaidAmount
            this.model.unpaidAmount = this.totalUnpaidAmount
          })

          this.$message.success('交易记录已添加，将在订单提交后保存')
          return
        }

        // 调用后端接口保存交易记录
        postAction('/oms/productSalesOrder/transaction/add', transactionData)
          .then((res) => {
            if (res.success) {
              // 重新加载交易记录
              this.loadTransactionRecords(this.model.id)
              this.$message.success('交易记录添加成功')

              // 更新模型中的已付款和待付款金额
              this.$nextTick(() => {
                // 更新表单中的已付款和待付款字段
                this.form.setFieldsValue({
                  paidAmount: this.totalPaidAmount,
                  unpaidAmount: this.totalUnpaidAmount,
                })

                // 同时更新模型对象
                this.model.paidAmount = this.totalPaidAmount
                this.model.unpaidAmount = this.totalUnpaidAmount
              })
            } else {
              this.$message.error(res.message || '添加交易记录失败')
            }
          })
          .catch((err) => {
            this.$message.error('添加交易记录失败: ' + err.message)
          })
      } else {
        // 准备更新的数据
        const transactionData = {
          id: record.id,
          productSalesOrderId: this.model.id, // 保持原字段名，后端会处理
          orderId: this.model.id, // 同时提供orderId字段以适配后端
          transactionType: record.transactionType ? parseInt(record.transactionType) : 1,
          paymentMethod: record.paymentMethod ? parseInt(record.paymentMethod) : 1,
          amount: parseFloat(record.amount),
          description: record.description,
          transactionPersonId: record.transactionPersonId,
          transactionVoucher: record.paymentVoucher || record.transactionVoucher, // 使用paymentVoucher或transactionVoucher
        }

        // 调用后端接口更新交易记录
        putAction('/oms/productSalesOrder/transaction/edit', transactionData)
          .then((res) => {
            if (res.success) {
              // 重新加载交易记录
              this.loadTransactionRecords(this.model.id)
              this.$message.success('交易记录更新成功')

              // 更新模型中的已付款和待付款金额
              this.$nextTick(() => {
                // 更新表单中的已付款和待付款字段
                this.form.setFieldsValue({
                  paidAmount: this.totalPaidAmount,
                  unpaidAmount: this.totalUnpaidAmount,
                })

                // 同时更新模型对象
                this.model.paidAmount = this.totalPaidAmount
                this.model.unpaidAmount = this.totalUnpaidAmount
              })
            } else {
              this.$message.error(res.message || '更新交易记录失败')
            }
          })
          .catch((err) => {
            this.$message.error('更新交易记录失败: ' + err.message)
          })
      }
    },

    cancelEdit(record, index) {
      // 如果是新记录，直接从列表中移除
      if (record.isNew) {
        this.transactionRecords.splice(index, 1)
      } else {
        // 恢复原始数据
        this.$set(this.transactionRecords, index, { ...this.tempTransaction, editable: false })
      }

      this.editingTransaction = null
      this.tempTransaction = {}
    },

    removeTransaction(record, index) {
      // 如果是新添加的记录，直接从列表中移除
      if (record.isNew) {
        this.transactionRecords.splice(index, 1)
        this.$message.success('交易记录已删除')

        // 更新临时交易记录数组
        if (!this.model.id) {
          this.tempTransactionRecords = [...this.transactionRecords]
        }

        // 更新模型中的已付款和待付款金额
        this.$nextTick(() => {
          // 更新表单中的已付款和待付款字段
          this.form.setFieldsValue({
            paidAmount: this.totalPaidAmount,
            unpaidAmount: this.totalUnpaidAmount,
          })

          // 同时更新模型对象
          this.model.paidAmount = this.totalPaidAmount
          this.model.unpaidAmount = this.totalUnpaidAmount
        })

        return
      }

      // 如果是已保存的记录，需要调用后端接口删除
      if (record.id) {
        deleteAction(`/oms/productSalesOrder/transaction/delete?id=${record.id}`)
          .then((res) => {
            if (res.success) {
              // 从列表中移除
              this.transactionRecords.splice(index, 1)
              this.$message.success('交易记录删除成功')

              // 更新预付款金额
              if (record.transactionType && parseInt(record.transactionType) === 1) {
                const currentPrepayment = parseFloat(this.form.getFieldValue('prepayment') || 0)
                const newPrepayment = Math.max(0, currentPrepayment - parseFloat(record.amount))
                this.form.setFieldsValue({ prepayment: newPrepayment })
                this.updateFinanceDataItem('prepayment', newPrepayment)
              }

              // 更新模型中的已付款和待付款金额
              this.$nextTick(() => {
                // 更新表单中的已付款和待付款字段
                this.form.setFieldsValue({
                  paidAmount: this.totalPaidAmount,
                  unpaidAmount: this.totalUnpaidAmount,
                })

                // 同时更新模型对象
                this.model.paidAmount = this.totalPaidAmount
                this.model.unpaidAmount = this.totalUnpaidAmount
              })
            } else {
              this.$message.error(res.message || '删除交易记录失败')
            }
          })
          .catch((err) => {
            this.$message.error('删除交易记录失败: ' + err.message)
          })
      }
    },

    // 添加下一步按钮点击处理方法
    goToNextStep() {
      console.log('点击下一步按钮')

      // 检查是否有解析结果
      if (!this.parseResult || !this.parseResult.details || this.parseResult.details.length === 0) {
        this.$message.warning('没有可用的解析数据，请先上传并解析文件')
        return
      }

      // 弹出确认数量对话框
      this.$confirm({
        title: '请确认产品数量',
        content: '您是否已确认所有产品的数量信息？确认后将进入下一步。',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          // 确保订单编号已经设置到model对象中
          if (this.parseResult.orderNo) {
            this.model.orderNo = this.parseResult.orderNo
          } else if (this.parseResult.orderId) {
            this.model.orderNo = this.parseResult.orderId
          } else {
            // 如果没有检测到订单号，提示用户
            this.$message.info('未检测到订单编号，请在下一步中手动填写')
          }

          // 将确认后的数量更新到detailDataSource
          this.parseResult.details.forEach((detail) => {
            detail.key = detail.id || this.generateUUID()
            // 确保数量字段有有效值
            if (!detail.quantity || detail.quantity < 1) {
              detail.quantity = 1
            }

            // 根据更新后的数量重新计算总面积
            if (detail.area) {
              detail.totalArea = (parseFloat(detail.area) * parseInt(detail.quantity)).toFixed(2)
            }
          })

          // 更新detailDataSource
          this.detailDataSource = [...this.parseResult.details]

          // 切换到订单信息页面
          this.activeKey = '1'

          // 确保表单中有日期值
          this.$nextTick(() => {
            // 再次确保订单编号已设置
            if (this.model.orderNo) {
              this.form.setFieldsValue({ orderNo: this.model.orderNo })
            }

            // 判断是否从解析结果中获取到了下单日期
            const hasOrderDate = this.parseResult.orderDate && this.parseResult.orderDate.trim() !== ''
            // 判断是否从解析结果中获取到了交付日期
            const hasDeliveryDate = this.parseResult.deliveryDate && this.parseResult.deliveryDate.trim() !== ''

            // 检查下单日期
            if (hasOrderDate) {
              try {
                // 尝试解析日期
                const orderDate = moment(this.parseResult.orderDate)
                if (orderDate.isValid()) {
                  this.form.setFieldsValue({ orderDate: orderDate })
                  console.log('成功设置下单日期:', orderDate.format('YYYY-MM-DD'))
                } else {
                  console.warn('无效的下单日期格式:', this.parseResult.orderDate)
                  this.form.setFieldsValue({ orderDate: moment() })
                  this.$message.warning('无法识别下单日期格式，已使用当前日期')
                }
              } catch (e) {
                console.error('解析下单日期出错:', e)
                this.form.setFieldsValue({ orderDate: moment() })
                this.$message.warning('解析下单日期时出错，已使用当前日期')
              }
            } else {
              // 如果表单中没有设置下单日期，则设置为今天
              this.form.setFieldsValue({ orderDate: moment() })
              console.log('未检测到下单日期，使用当前日期')
              this.$message.info('未检测到下单日期，请确认日期是否正确')
            }

            // 检查交付日期
            if (hasDeliveryDate) {
              try {
                // 尝试解析日期
                const deliveryDate = moment(this.parseResult.deliveryDate)
                if (deliveryDate.isValid()) {
                  this.form.setFieldsValue({ deliveryDate: deliveryDate })
                  console.log('成功设置交付日期:', deliveryDate.format('YYYY-MM-DD'))
                } else {
                  console.warn('无效的交付日期格式:', this.parseResult.deliveryDate)
                  // 默认交付日期为下单日期+30天
                  const orderDate = this.form.getFieldValue('orderDate')
                  this.form.setFieldsValue({
                    deliveryDate: orderDate ? moment(orderDate).add(30, 'days') : moment().add(30, 'days'),
                  })
                  this.$message.warning('无法识别交付日期格式，已使用下单日期+30天')
                }
              } catch (e) {
                console.error('解析交付日期出错:', e)
                // 默认交付日期为下单日期+30天
                const orderDate = this.form.getFieldValue('orderDate')
                this.form.setFieldsValue({
                  deliveryDate: orderDate ? moment(orderDate).add(30, 'days') : moment().add(30, 'days'),
                })
                this.$message.warning('解析交付日期时出错，已使用下单日期+30天')
              }
            } else {
              // 如果表单中没有设置交付日期，则设置为今天+30天
              const orderDate = this.form.getFieldValue('orderDate')
              this.form.setFieldsValue({
                deliveryDate: orderDate ? moment(orderDate).add(30, 'days') : moment().add(30, 'days'),
              })
              console.log('未检测到交付日期，使用下单日期+30天')
              this.$message.info('未检测到交付日期，请确认日期是否正确')
            }

            // 提示用户继续填写其他订单信息
            this.$message.info('请继续填写客户和其他订单信息')
          })
        },
      })
    },

    // 处理数量变更
    handleQuantityChange(record, value, index) {
      if (!record || value < 1) return

      // 更新数量
      this.$set(this.parseResult.details[index], 'quantity', value)

      // 如果有面积信息，则重新计算总面积
      if (record.area) {
        const totalArea = (parseFloat(record.area) * value).toFixed(2)
        this.$set(this.parseResult.details[index], 'totalArea', totalArea)
      }

      console.log(
        `窗号 ${record.windowNo} 的数量已更新为 ${value}，总面积更新为 ${this.parseResult.details[index].totalArea}`
      )
    },

    // 处理人员选择变更
    handlePersonChange(value, option, record) {
      console.log('人员选择变更:', value, option)
      if (option && option.length > 0) {
        // JSelectEmployeeModal返回的是员工数组
        const selectedEmployee = option[0]
        record.transactionPersonName = selectedEmployee.empName
        console.log('已更新人员信息:', record.transactionPersonId, record.transactionPersonName)
      } else if (value) {
        // 如果没有获取到人员名称，尝试通过API获取
        getAction('/sys/employee/getEmployeeById', { id: value })
          .then((res) => {
            if (res.success && res.result) {
              record.transactionPersonName = res.result.empName
              console.log('通过API获取人员名称:', record.transactionPersonName)
            }
          })
          .catch((err) => {
            console.error('获取人员名称失败:', err)
          })
      }
    },

    // 添加提交临时交易记录的方法
    submitTempTransactions(orderId) {
      if (!orderId || this.tempTransactionRecords.length === 0) {
        return
      }

      console.log('提交临时交易记录，订单ID:', orderId)

      // 过滤出非编辑状态的交易记录
      const validTransactions = this.tempTransactionRecords.filter((record) => !record.editable)

      if (validTransactions.length === 0) {
        console.log('没有有效的临时交易记录需要提交')
        return
      }

      console.log('有效的临时交易记录:', validTransactions.length, '条')

      // 批量提交交易记录
      const promises = validTransactions.map((record) => {
        // 准备交易数据
        const transactionData = {
          productSalesOrderId: orderId,
          orderId: orderId,
          transactionType: record.transactionType ? parseInt(record.transactionType) : 1,
          paymentMethod: record.paymentMethod ? parseInt(record.paymentMethod) : 1,
          amount: parseFloat(record.amount),
          description:
            record.description ||
            this.getTransactionDescription(record.transactionType ? parseInt(record.transactionType) : 1),
          transactionPersonId: record.transactionPersonId,
          transactionVoucher: record.paymentVoucher || record.transactionVoucher,
          transactionTime: record.transactionTime || moment().format('YYYY-MM-DD HH:mm:ss'),
        }

        // 提交单条交易记录
        return postAction('/oms/productSalesOrder/transaction/add', transactionData)
      })

      // 等待所有交易记录提交完成
      Promise.all(promises)
        .then((results) => {
          const successCount = results.filter((res) => res.success).length
          console.log(`成功提交${successCount}/${validTransactions.length}条交易记录`)

          if (successCount > 0) {
            this.$message.success(`成功提交${successCount}条交易记录`)
          }

          if (successCount < validTransactions.length) {
            this.$message.warning(`${validTransactions.length - successCount}条交易记录提交失败`)
          }

          // 清空临时交易记录
          this.tempTransactionRecords = []
        })
        .catch((err) => {
          console.error('提交临时交易记录失败:', err)
          this.$message.error('提交交易记录失败')
        })
    },

    // 添加销售总额编辑模态框相关方法
    showTotalAmountModal() {
      this.totalAmountModalVisible = true
    },

    handleTotalAmountOk() {
      this.totalAmountForm.validateFields((err, values) => {
        if (!err) {
          this.model.totalAmount = values.totalAmount
          this.updateFinanceDataItem('totalAmount', values.totalAmount)
          this.totalAmountModalVisible = false
          this.$message.success('销售总额更新成功')
        }
      })
    },

    handleTotalAmountCancel() {
      this.totalAmountModalVisible = false
      this.totalAmountForm.resetFields()
    },

    // 添加成本汇总编辑模态框相关方法
    showTotalCostModal() {
      this.totalCostModalVisible = true
    },

    handleTotalCostOk() {
      this.totalCostForm.validateFields((err, values) => {
        if (!err) {
          this.model.totalCost = values.totalCost
          this.updateFinanceDataItem('totalCost', values.totalCost)
          this.totalCostModalVisible = false
          this.$message.success('成本汇总更新成功')
        }
      })
    },

    handleTotalCostCancel() {
      this.totalCostModalVisible = false
      this.totalCostForm.resetFields()
    },

    // 订单进度相关方法
    // 加载订单进度记录
    loadProgressList(orderId) {
      if (!orderId) return

      this.confirmLoading = true
      getAction('/oms/productSalesOrder/progress/list', { orderId: orderId })
        .then((res) => {
          if (res.success) {
            console.log('获取进度记录成功:', res.result)
            // 处理返回的数据
            if (res.result && res.result.records) {
              this.progressList = res.result.records
              // 获取所有进度记录的操作人信息
              this.progressList.forEach((progress) => {
                this.getOperatorInfo(progress)
              })
            } else {
              this.progressList = []
            }
          } else {
            console.error('获取进度记录失败:', res.message)
            this.$message.error('获取进度记录失败: ' + res.message)
            this.progressList = []
          }
          this.confirmLoading = false
        })
        .catch((err) => {
          console.error('获取进度记录异常:', err)
          this.$message.error('获取进度记录失败')
          this.progressList = []
          this.confirmLoading = false
        })
    },

    // 获取所有操作人的员工名称
    processOperatorNames() {
      if (!this.progressList || this.progressList.length === 0) return

      const createBySet = new Set()

      // 收集所有createBy值（userId）
      this.progressList.forEach((item) => {
        if (item.createBy && (!this.userCache || !this.userCache[item.createBy])) {
          createBySet.add(item.createBy)
        }
      })

      // 批量获取用户信息
      const promises = Array.from(createBySet).map((userId) => {
        return this.getEmployeeNameByUserId(userId)
      })

      Promise.all(promises).then(() => {
        // 更新列表中的操作人展示
        this.progressList.forEach((item) => {
          if (item.createBy && this.userCache && this.userCache[item.createBy]) {
            item.operatorName = this.userCache[item.createBy]
          }
        })
      })
    },

    // 通过createBy(userId)获取员工真实姓名
    getEmployeeNameByUserId(userId) {
      // 如果缓存中存在，直接返回
      if (this.userCache && this.userCache[userId]) {
        return Promise.resolve(this.userCache[userId])
      }

      // 确保userCache存在
      if (!this.userCache) {
        this.userCache = {}
      }

      return new Promise((resolve) => {
        getAction('/sys/employee/queryById', { id: userId })
          .then((res) => {
            if (res.success && res.result) {
              const empName = res.result.empName || '未知员工'
              // 缓存用户信息
              this.userCache[userId] = empName
              resolve(empName)
            } else {
              this.userCache[userId] = '未知员工'
              resolve('未知员工')
            }
          })
          .catch(() => {
            this.userCache[userId] = '未知员工'
            resolve('未知员工')
          })
      })
    },

    // 保存进度记录
    handleProgressOk() {
      this.progressForm.validateFields((err, values) => {
        if (err) {
          return
        }

        // 处理时间格式
        values.progressTime = values.progressTime
          ? values.progressTime.format('YYYY-MM-DD HH:mm:ss')
          : moment().format('YYYY-MM-DD HH:mm:ss')

        // 添加订单ID
        values.orderId = this.model.id

        if (this.currentProgress && this.currentProgress.id) {
          // 编辑模式
          values.id = this.currentProgress.id

          this.confirmLoading = true
          putAction('/oms/productSalesOrder/progress/edit', values)
            .then((res) => {
              if (res.success) {
                // 更新列表中的数据
                this.$set(this.progressList, this.progressEditIndex, res.result)
                // 获取操作人信息
                this.getOperatorInfo(res.result)
                this.$message.success('进度记录更新成功')
                this.progressModalVisible = false
              } else {
                this.$message.error('更新失败: ' + res.message)
              }
              this.confirmLoading = false
            })
            .catch((err) => {
              console.error('更新进度记录异常:', err)
              this.$message.error('更新失败')
              this.confirmLoading = false
            })
        } else {
          // 添加模式
          this.confirmLoading = true
          postAction('/oms/productSalesOrder/progress/add', values)
            .then((res) => {
              if (res.success) {
                // 获取操作人信息
                this.getOperatorInfo(res.result)
                // 添加到列表
                this.progressList.unshift(res.result)
                this.$message.success('进度记录添加成功')
                this.progressModalVisible = false
              } else {
                this.$message.error('添加失败: ' + res.message)
              }
              this.confirmLoading = false
            })
            .catch((err) => {
              console.error('添加进度记录异常:', err)
              this.$message.error('添加失败')
              this.confirmLoading = false
            })
        }
      })
    },

    // 取消进度记录编辑
    handleProgressCancel() {
      this.progressModalVisible = false
      this.progressForm.resetFields()
      this.currentProgress = null
      this.progressEditIndex = -1
    },

    // 获取操作人信息
    getOperatorInfo(progress) {
      if (!progress || !progress.createBy) return

      getAction('/sys/employee/queryByUsername', { username: progress.createBy })
        .then((res) => {
          if (res.success && res.result) {
            progress.operatorName = res.result.empName
            // 强制更新视图
            this.$forceUpdate()
          }
        })
        .catch((err) => {
          console.error('获取操作人信息失败:', err)
        })
    },

    // 获取订单状态类型
    getOrderStatusType(status) {
      switch (parseInt(status)) {
        case 0:
          return 'default' // 新增订单-待审核
        case 1:
          return 'processing' // 审核通过-待上传
        case 2:
          return 'processing' // 已上传汇总单-待上传优化单
        case 3:
          return 'processing' // 已上传优化单-待提交审核
        case 4:
          return 'processing' // 待下发
        case 5:
          return 'processing' // 领料单待审核
        case 6:
          return 'processing' // 待领料
        case 7:
          return 'processing' // 生产中
        case 8:
          return 'success' // 已完成
        case 9:
          return 'error' // 已取回
        default:
          return 'default'
      }
    },

    // 获取订单状态文本
    getOrderStatusText(status) {
      if (status === undefined || status === null) {
        return '未知状态'
      }

      // 将status转换为字符串，然后转为数字
      const statusNum = parseInt(status.toString())

      switch (statusNum) {
        case 0:
          return '新增订单-待审核'
        case 1:
          return '审核通过-待上传'
        case 2:
          return '已上传汇总单-待上传优化单'
        case 3:
          return '已上传优化单-待提交审核'
        case 4:
          return '待下发'
        case 5:
          return '领料单待审核'
        case 6:
          return '待领料'
        case 7:
          return '生产中'
        case 8:
          return '已完成'
        case 9:
          return '已取回'
        default:
          return '未知状态(' + status + ')'
      }
    },

    // 查看产品详情信息
    handleViewDetailInfo(record) {
      if (!record || !record.id) {
        this.$message.warning('无法获取产品详情，缺少产品ID')
        return
      }

      this.currentDetailRecord = record

      // 获取订单优化软件类型，并设置isChangfengType计算属性所需的参数
      const orderRecord = this.model || {}
      const optimizationSoftwareType = orderRecord.optimizationSoftwareType || '0' // 默认为长风(0)

      // 设置详情记录的优化软件类型，确保计算属性能正确获取
      this.currentDetailRecord.optimizationSoftwareType = optimizationSoftwareType

      this.detailInfoVisible = true
      this.detailInfoLoading = true

      console.log('查看详情', record.id, '优化软件类型:', optimizationSoftwareType, '窗号:', record.windowNo)

      // 并行加载三种数据
      const detailId = record.id
      const windowNo = record.windowNo || ''
      Promise.all([
        this.loadAccessoriesData(detailId, windowNo),
        this.loadGlassSizeData(detailId, windowNo),
        this.loadProfileSizeData(detailId, windowNo),
      ])
        .then(() => {
          this.detailInfoLoading = false
        })
        .catch((error) => {
          console.error('加载产品详情数据失败:', error)
          this.$message.error('加载产品详情数据失败')
          this.detailInfoLoading = false
        })
    },

    // 加载配件数据
    loadAccessoriesData(detailId, windowNo) {
      return new Promise((resolve, reject) => {
        if (!detailId) {
          this.accessoriesList = []
          resolve()
          return
        }

        const apiUrl = this.url.loadAccessories
        const params = {
          detailId: detailId,
          softwareType: this.isChangfengType ? '0' : '1',
          windowNo: windowNo || '',
        }

        getAction(apiUrl, params)
          .then((res) => {
            if (res.success) {
              this.accessoriesList = res.result || []
              resolve()
            } else {
              this.$message.warning('获取配件信息失败: ' + (res.message || '未知错误'))
              this.accessoriesList = []
              resolve() // 即使失败也继续执行
            }
          })
          .catch((err) => {
            console.error('获取配件信息异常:', err)
            this.accessoriesList = []
            resolve() // 即使失败也继续执行
          })
      })
    },

    // 加载玻璃尺寸数据
    loadGlassSizeData(detailId, windowNo) {
      return new Promise((resolve, reject) => {
        if (!detailId) {
          this.glassSizeList = []
          resolve()
          return
        }
        console.log(this.isChangfengType)

        const apiUrl = this.url.loadGlassSize
        const params = {
          detailId: detailId,
          softwareType: this.isChangfengType ? '0' : '1',
          windowNo: windowNo || '',
        }

        getAction(apiUrl, params)
          .then((res) => {
            if (res.success) {
              this.glassSizeList = res.result || []
              resolve()
            } else {
              this.$message.warning('获取玻璃尺寸信息失败: ' + (res.message || '未知错误'))
              this.glassSizeList = []
              resolve() // 即使失败也继续执行
            }
          })
          .catch((err) => {
            console.error('获取玻璃尺寸信息异常:', err)
            this.glassSizeList = []
            resolve() // 即使失败也继续执行
          })
      })
    },

    // 加载型材尺寸数据
    loadProfileSizeData(detailId, windowNo) {
      return new Promise((resolve, reject) => {
        if (!detailId) {
          this.profileSizeList = []
          resolve()
          return
        }

        const apiUrl = this.url.loadProfileSize
        const params = {
          detailId: detailId,
          softwareType: this.isChangfengType ? '0' : '1',
          windowNo: windowNo || '',
        }

        getAction(apiUrl, params)
          .then((res) => {
            if (res.success) {
              this.profileSizeList = res.result || []
              resolve()
            } else {
              this.$message.warning('获取型材尺寸信息失败: ' + (res.message || '未知错误'))
              this.profileSizeList = []
              resolve() // 即使失败也继续执行
            }
          })
          .catch((err) => {
            console.error('获取型材尺寸信息异常:', err)
            this.profileSizeList = []
            resolve() // 即使失败也继续执行
          })
      })
    },

    // 关闭详情弹窗
    closeDetailInfoModal() {
      this.detailInfoVisible = false
      this.currentDetailRecord = null
      this.accessoriesList = []
      this.glassSizeList = []
      this.profileSizeList = []
    },
  },
}
</script>

<style lang="less" scoped>
.upload-file-container {
  padding: 16px;

  .upload-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;

    .upload-title {
      font-size: 16px;
      font-weight: 500;
    }

    .upload-desc {
      color: #999;
    }
  }

  .upload-area {
    margin-bottom: 16px;

    .upload-api-url {
      margin-top: 8px;
      font-size: 12px;
      color: #999;
      word-break: break-all;
    }
  }

  .upload-status {
    margin-bottom: 16px;
  }

  .parse-result {
    margin-top: 24px;
  }
}

/* 表格样式增强 */
::v-deep .ant-table-wrapper {
  .ant-table-tbody > tr > td {
    background-color: #fff;
  }

  .ant-table-thead > tr > th {
    background-color: #f5f5f5;
    font-weight: 500;
  }
}

/* 产品详情表格样式修复 */
::v-deep .ant-table {
  table-layout: fixed !important;
}

::v-deep .ant-table-scroll {
  overflow-x: auto !important;
}

::v-deep .ant-table-header-column {
  display: inline-block;
  width: 100% !important;
}

::v-deep .ant-table-body {
  overflow-x: auto !important;
}

/* 统一下拉框和输入框样式 */
::v-deep .ant-select {
  width: 100% !important;
}

::v-deep .ant-select-selection--single {
  height: 32px;
}

::v-deep .ant-input,
::v-deep .ant-input-number {
  width: 100% !important;
}

::v-deep .ant-form-item-control {
  width: 100%;
}

// 图纸相关样式
.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.drawing-preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 600px;
  background: #f0f2f5;
  border-radius: 4px;
  overflow: hidden;

  .drawing-preview-image {
    max-width: 100%;
    max-height: 600px;
    object-fit: contain;
  }

  .drawing-preview-iframe {
    width: 100%;
    height: 600px;
    border: none;
  }
}

.drawing-thumbnail-container {
  cursor: pointer;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 4px;
  border: 1px solid transparent;
  border-radius: 4px;
  transition: all 0.3s;

  .drawing-thumbnail {
    max-width: 60px;
    max-height: 40px;
    object-fit: contain;
    border: 1px solid #eee;
  }

  .file-icon {
    font-size: 24px;
    color: #1890ff;
  }

  .thumbnail-filename {
    font-size: 12px;
    color: #666;
    margin-top: 4px;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
  }

  &:hover {
    background-color: #f0f7ff;
    border-color: #1890ff;

    .drawing-thumbnail {
      border-color: #1890ff;
    }

    .file-icon {
      color: #40a9ff;
    }

    .thumbnail-filename {
      color: #1890ff;
    }
  }
}

/* 解析结果表格中的图片样式 */
.parse-result .drawing-thumbnail-container {
  .drawing-thumbnail {
    max-width: 80px;
    max-height: 60px;
  }
}

/* 表格滚动样式 */
.ant-table-wrapper {
  .ant-table-body {
    overflow-x: auto !important;
    overflow-y: auto !important;
  }
}

/* 优化布局 */
.product-order-modal-container {
  display: flex;
}

.left-container {
  flex: 1;
  margin-right: 16px;
}

.right-container {
  width: 35%;
  background-color: #fff;
}

.payment-tip {
  margin-top: 5px;
  color: #1890ff;
  font-size: 12px;

  .anticon {
    margin-right: 5px;
  }
}

/* 支付凭证上传区域高亮动画 */
@keyframes highlight-blink {
  0% {
    box-shadow: 0 0 5px rgba(24, 144, 255, 0.5);
  }
  50% {
    box-shadow: 0 0 15px rgba(24, 144, 255, 0.8);
  }
  100% {
    box-shadow: 0 0 5px rgba(24, 144, 255, 0.5);
  }
}

.highlight-upload {
  animation: highlight-blink 1.5s ease-in-out infinite;
  padding: 8px;
  border-radius: 4px;
  border: 1px dashed #1890ff;
  transition: all 0.3s;
}

.transaction-table-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;

  .ant-btn {
    border-radius: 4px;
    box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);

    &:hover,
    &:focus {
      transform: translateY(-1px);
      box-shadow: 0 3px 0 rgba(0, 0, 0, 0.045);
    }

    &:active {
      transform: translateY(1px);
      box-shadow: 0 1px 0 rgba(0, 0, 0, 0.045);
    }
  }
}

// 添加表格滚动样式
::v-deep .ant-table-body {
  max-height: 300px !important;
  overflow-y: auto !important;
  overflow-x: auto !important;
}

::v-deep .ant-table-fixed-header > .ant-table-content > .ant-table-scroll > .ant-table-body {
  max-height: 300px !important;
}

// 财务概览表格样式
::v-deep .finance-overview-table .ant-table-body {
  max-height: 180px !important;
}

// 财务表格通用样式
::v-deep .finance-table {
  // 表头样式
  .ant-table-thead > tr > th {
    background-color: #e6f7ff;
    color: #1890ff;
    font-weight: 600;
    text-align: center;
    padding: 12px 8px;
  }

  // 表体单元格样式
  .ant-table-tbody > tr > td {
    padding: 10px 8px;
    transition: all 0.3s;
  }

  // 表格行悬停效果
  .ant-table-tbody > tr:hover > td {
    background-color: #f0f7ff !important;
  }

  // 金额右对齐
  .ant-table-tbody > tr > td.amount-column,
  .ant-table-thead > tr > th.amount-column {
    text-align: right;
  }
}

// 交易记录表格特殊样式
::v-deep .transaction-table {
  margin-top: 12px;

  // 表头和表体单元格居中对齐
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    text-align: center;
  }

  // 操作列样式
  .action-column {
    white-space: nowrap;
    min-width: 120px;
    text-align: center;
  }

  // 交易描述样式 - 保持左对齐
  .description-column {
    max-width: 200px;
    word-break: break-all;
    text-align: left;
  }

  // 金额列 - 保持右对齐
  .amount-column {
    text-align: right;
  }

  // 为表格添加斑马纹
  .ant-table-tbody > tr:nth-child(even) > td {
    background-color: #fafafa;
  }

  // 调整交易记录表格中的按钮样式
  .action-btn {
    margin-right: 8px;

    &:last-child {
      margin-right: 0;
    }
  }
}

// 修改交易记录表格的金额显示样式
::v-deep .transaction-table {
  .amount-value {
    font-weight: 500;
    color: #333;

    &.positive {
      color: #52c41a !important;
    }

    &.negative {
      color: #f5222d !important;
    }
  }

  // 优化交易类型和支付方式标签样式
  .ant-tag {
    margin-right: 0;
    text-align: center;
  }

  // 优化凭证链接样式
  .voucher-link {
    color: #1890ff;
    cursor: pointer;

    &:hover {
      color: #40a9ff;
      text-decoration: underline;
    }
  }
}

.description-content {
  max-width: 200px;
  word-break: break-all;

  span {
    display: inline-block;
    line-height: 1.5;
  }
}

// 交易描述样式优化
::v-deep .transaction-table {
  .description-column {
    max-width: 200px;

    // 描述为空时的样式
    .empty-description {
      color: #999;
      font-style: italic;
      font-size: 12px;
    }

    // 编辑状态下的文本区域样式
    .ant-input {
      border-color: #d9d9d9;

      &:hover {
        border-color: #40a9ff;
      }

      &:focus {
        border-color: #40a9ff;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
      }
    }
  }
}

::v-deep .description-textarea {
  border-radius: 4px;
  resize: none;

  &:hover {
    border-color: #40a9ff;
  }

  &:focus {
    border-color: #40a9ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    outline: none;
  }
}

::v-deep .description-column {
  .ant-tooltip-inner {
    max-width: 300px;
    white-space: pre-wrap;
  }
}

// 交易记录表格高级样式
::v-deep .finance-tab-content .transaction-table {
  // 表格边框样式
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 12px;

  // 设置适中的行高，使表格更紧凑
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    height: 46px;
  }

  // 表头样式增强
  .ant-table-thead > tr > th {
    background-color: #e6f7ff;
    font-weight: 600;
    border-bottom: 2px solid #1890ff;
    font-size: 14px;
  }

  // 增强表格边框
  .ant-table-tbody > tr > td {
    border-bottom: 1px solid #f0f0f0;
    transition: all 0.3s ease;
  }

  // 表格最后一行取消边框
  .ant-table-tbody > tr:last-child > td {
    border-bottom: none;
  }
}

// 添加产品明细表格样式
::v-deep .ant-table-bordered {
  // 表头和表体单元格居中对齐
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    text-align: center;
  }

  // 产品明细表格表头样式
  .ant-table-thead > tr > th {
    background-color: #e6f7ff;
    color: #1890ff;
    font-weight: 600;
    padding: 12px 8px;
    border-bottom: 2px solid #1890ff;
  }

  // 产品明细表格添加斑马纹
  .ant-table-tbody > tr:nth-child(even) > td {
    background-color: #fafafa;
  }

  // 表格行悬停效果
  .ant-table-tbody > tr:hover > td {
    background-color: #f0f7ff !important;
  }
}

.voucher-thumbnail-container {
  cursor: pointer;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 4px;
  border: 1px solid transparent;
  border-radius: 4px;
  transition: all 0.3s;

  .voucher-thumbnail {
    max-width: 60px;
    max-height: 40px;
    object-fit: contain;
    border: 1px solid #eee;
    border-radius: 2px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }

  &:hover {
    background-color: #f0f7ff;
    border-color: #1890ff;

    .voucher-thumbnail {
      border-color: #1890ff;
      transform: scale(1.05);
    }
  }
}

// 优化凭证链接样式
::v-deep .voucher-link {
  color: #1890ff;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 2px;
  border: 1px solid #e8e8e8;
  background: #f5f5f5;
  transition: all 0.3s;

  &:hover {
    color: #40a9ff;
    border-color: #40a9ff;
    background: #f0f7ff;
  }
}

// 添加表格强制不换行样式
::v-deep .j-table-force-nowrap {
  table {
    table-layout: fixed;
    width: 100% !important;
  }

  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .ant-table-header-column {
    display: inline-block;
    width: 100%;
  }

  .ant-table-body {
    overflow-x: auto !important;
  }
}

// 优化表格列宽样式
::v-deep .transaction-table {
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    padding: 12px 8px;
  }

  // 确保表头和表体对齐
  .ant-table-header {
    overflow: hidden !important;
    margin-bottom: 0 !important;

    table {
      margin-bottom: 0 !important;
    }
  }

  // 确保表格内容不会被挤压
  .ant-table-body {
    overflow-y: auto !important;
    overflow-x: auto !important;
  }
}

/* 订单进度相关样式 */
.progress-container {
  padding: 16px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.progress-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.order-progress-timeline {
  margin-top: 24px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 4px;
}

.order-progress-timeline .ant-timeline-item {
  padding-bottom: 20px;
}

.order-progress-timeline .ant-timeline-item:last-child {
  padding-bottom: 0;
}

.progress-item {
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 8px;
  transition: all 0.3s;
}

.progress-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.progress-item.latest-item {
  border-left: 3px solid #1890ff;
  background-color: #f0f7ff;
}

.progress-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.progress-main-info {
  display: flex;
  align-items: center;
}

.progress-time {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
  margin-left: 10px;
}

.progress-type {
  font-weight: bold;
  text-align: center;
}

.progress-type .ant-tag {
  margin-right: 0;
  padding: 0 8px;
  font-weight: 500;
}

.progress-actions {
  display: flex;
}

.progress-actions a {
  margin-left: 8px;
}

.progress-content {
  margin-bottom: 12px;
  padding: 8px 12px;
  background-color: #f9f9f9;
  border-radius: 4px;
  white-space: pre-wrap;
  line-height: 1.6;
  color: rgba(0, 0, 0, 0.65);
}

.progress-reason {
  display: flex;
  margin-bottom: 8px;
}

.progress-new-status {
  display: flex;
  margin-top: 8px;
}

.reason-label,
.status-label {
  font-weight: 500;
  margin-right: 8px;
  min-width: 70px;
}

.reason-content,
.status-content {
  flex: 1;
  word-break: break-all;
}

.progress-footer {
  color: #888;
  font-size: 12px;
  text-align: right;
  display: flex;
  justify-content: space-between;
}

.progress-operator {
  color: rgba(0, 0, 0, 0.45);
}

.update-time {
  color: rgba(0, 0, 0, 0.45);
  font-style: italic;
}

.empty-progress {
  padding: 24px 0;
  text-align: center;
}

.order-status-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  margin-bottom: 20px;
}

.order-status-card .ant-card-head {
  border-bottom: 1px solid #f0f0f0;
  padding: 0 16px;
  min-height: 48px;
}

.order-status-card .ant-card-head-title {
  padding: 12px 0;
  font-size: 16px;
  font-weight: 500;
}

.order-status-card .ant-card-body {
  padding: 16px;
}

.order-status-content {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.status-badge {
  margin-right: 24px;
  min-width: 100px;
}

.status-badge .ant-badge-status-text,
.status-badge .badge-text {
  font-size: 16px;
  font-weight: 500;
  color: #1890ff;
}

.status-info {
  flex: 1;
}

.latest-progress {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.latest-label {
  margin-right: 8px;
  color: rgba(0, 0, 0, 0.65);
}

.latest-time {
  margin-left: 10px;
  color: rgba(0, 0, 0, 0.45);
}

// 防止在标签页切换时布局跳动
.finance-tab-content {
  min-height: 600px;
  position: relative;
}

::v-deep .finance-tab-content {
  .ant-card {
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);

    .ant-card-head {
      border-bottom: 1px solid #e8e8e8;
      padding: 0 16px;

      .ant-card-head-title {
        padding: 12px 0;
        font-size: 16px;
        color: #333;
        font-weight: 600;
      }
    }

    .ant-card-body {
      padding: 16px;
    }
  }
}

.detail-text {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

// 修复表格表头和内容错位问题
::v-deep .ant-table-bordered {
  .ant-table-header {
    overflow: hidden !important;
    margin-bottom: 0 !important;
  }

  .ant-table-header-column {
    width: 100%;
    display: inline-block;
  }

  .ant-table-body {
    overflow-x: auto !important;
  }

  table {
    width: 100% !important;
  }
}

/* 产品详情表格样式修复 */
::v-deep .ant-table-wrapper {
  .ant-table {
    table-layout: fixed;
    width: 100% !important;
  }

  .ant-table-header-column {
    display: inline-block !important;
    width: 100% !important;
  }

  .ant-table-body {
    overflow-x: auto !important;
  }

  .ant-table-thead > tr > th {
    white-space: nowrap;
    background-color: #f5f5f5;
    font-weight: 500;
  }

  .ant-table-tbody > tr > td {
    white-space: nowrap;
    background-color: #fff;
  }
}
</style>

}
</style>
